Binary search on the slope
Time O(log n) Space O(1)Rising at mid → peak is right of mid; otherwise mid or left.
arr = [0, 10, 5, 2]Step 1/3mid = 1. arr[1] = 10 is bigger than arr[2] = 5: we are going downhill, so the top is at mid or to its left. hi = 1.
class Solution {
public int peakIndexInMountainArray(int[] arr) {
int lo = 0, hi = arr.length - 1;
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (arr[mid] < arr[mid + 1]) lo = mid + 1; else hi = mid;
}
return lo;
}
}Verdict: The discrete ternary search.