(This problem is an interactive problem.)
You may recall that an array A is a mountain array if and only if:
A.length >= 3- There exists some
iwith0 < i < A.length - 1such that:A[0] < A[1] < ... A[i-1] < A[i]A[i] > A[i+1] > ... > A[A.length - 1]
Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index doesn't exist, return -1.
You can't access the mountain array directly. You may only access the array using a MountainArray interface:
MountainArray.get(k)returns the element of the array at indexk(0-indexed).MountainArray.length()returns the length of the array.
Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.
Example 1:
Input: array = [1,2,3,4,5,3,1], target = 3
Output: 2
Explanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.
Example 2:
Input: array = [0,1,2,4,2,1], target = 3
Output: -1
Explanation: 3 does not exist in the array, so we return -1.
Constraints:
3 <= mountain_arr.length() <= 100000 <= target <= 10^90 <= mountain_arr.get(index) <= 10^9
题目链接:https://leetcode-cn.com/problems/find-in-mountain-array/
思路
2次二分法使用:第一次用来找山峰,第二次向山峰左右分别二分查找目标。
!注意:山峰左右的二分法,范围减小时的方向不一样。
class Solution {
int binary_search(MountainArray &mountain, int target, int l, int r, bool revert) {
while (l <= r) {
int mid = (l + r) / 2;
int cur = mountain.get(mid);
if (cur == target)
return mid;
if(revert){
if(cur < target) {
r = mid - 1;
}else{
l = mid + 1;
}
}else{
if (cur < target)
l = mid + 1;
else
r = mid - 1;
}
}
return -1;
}
public:
int findInMountainArray(int target, MountainArray &mountainArr) {
int l = 0, r = mountainArr.length() - 1;
while (l < r) {
int mid = (l + r) / 2;
if (mountainArr.get(mid) < mountainArr.get(mid + 1))
l = mid + 1;
else
r = mid;
}
int peak = l;
int index = binary_search(mountainArr, target, 0, peak, false);
if (index != -1)
return index;
return binary_search(mountainArr, target, peak + 1, mountainArr.length()-1, true);
}
};
253




被折叠的 条评论
为什么被折叠?



