Problem:
Peak Index in a Mountain Array
Let's call an array A a mountain if the following properties hold:
A.length >= 3
There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1].
Example 1:
Input: [0,1,0]
Output: 1
Example 2:
Input: [0,2,1,0]
Output: 1
Note:
3 <= A.length <= 10000
0 <= A[i] <= 10^6
A is a mountain, as defined above.
Solution:
We can use binary search to find the peak.
class Solution {
public static void main(String...args) {
int[] arr = new int[]{0,2,1,0};
int r = solve(arr);
System.out.println(r);
}
private static int solve(int[] arr) { //1 2 3 4 5 7 3
int lo = 0; //4
int hi = arr.length - 1; //6
while(lo < hi) {
int mid = lo + (hi - lo)/2; //5
if(arr[mid-1] < arr[mid] && arr[mid] < arr[mid+1]) {
lo = mid + 1;
} else if (arr[mid-1] > arr[mid] && arr[mid] > arr[mid+1]) {
hi = mid;
} else {
return mid;
}
}
return lo;
}
}
public static void main(String...args) {
int[] arr = new int[]{0,2,1,0};
int r = solve(arr);
System.out.println(r);
}
private static int solve(int[] arr) { //1 2 3 4 5 7 3
int lo = 0; //4
int hi = arr.length - 1; //6
while(lo < hi) {
int mid = lo + (hi - lo)/2; //5
if(arr[mid-1] < arr[mid] && arr[mid] < arr[mid+1]) {
lo = mid + 1;
} else if (arr[mid-1] > arr[mid] && arr[mid] > arr[mid+1]) {
hi = mid;
} else {
return mid;
}
}
return lo;
}
}
The time complexity is O(logN) and the space complexity is O(1).