二分查找
- 使用二分查找查找山脉数组的峰值位置
- 将数组以峰值位置为分界线分为左右两部分,并分别使用二分查找查询目标值
二分查找就是每次查找将范围缩小一半
/**
* // This is MountainArray's API interface.
* // You should not implement it, or speculate about its implementation
* interface MountainArray {
* public int get(int index) {}
* public int length() {}
* }
*/
class Solution {
public int findInMountainArray(int target, MountainArray mountainArr) {
int n = mountainArr.length();
int left = 0, right = n-1;
while (left < right) {
int mid = (left + right) / 2;
if (mountainArr.get(mid) < mountainArr.get(mid + 1)) {
left = mid + 1;
} else {
right = mid;
}
}
int peek = left;
int index = binarySearch(target, mountainArr, 0, peek, true);
if (index != -1) {
return index;
}
return binarySearch(target, mountainArr, peek + 1, n - 1, false);
}
// flag true:递增 false: 递减
private int binarySearch(int target, MountainArray mountainArr, int left, int right, boolean flag) {
if (!flag) {
target *= -1;
}
while (left <= right) {
int mid = (left + right) / 2;
int cur = mountainArr.get(mid) * (flag ? 1 : -1);
if (cur > target) {
right = mid - 1;
} else if (cur < target) {
left = mid + 1;
} else {
return mid;
}
}
return -1;
}
}