Thinking process
The given two conditions imply there must be a peak.
Discuss different cases
- if it is the peak, then return
- if the left is smaller than current, then move start position to curr
- if the right is smaller than current, then move end position to curr
Mistakes
if length of A is 1, return 0;
if length of A is 2, return the largest;
class Solution {
/**
* @param A: An integers array.
* @return: return any of peek positions.
*/
public int findPeak(int[] A) {
// write your code here
if (A == null || A.length <= 2) {
return 0;
}
int start = 1;
int end = A.length - 2;
while (start + 1 < end) {
int mid = (end - start) / 2 + start;
if (A[mid] > A[mid - 1] && A[mid] > A[mid + 1]) {
return mid;
} else if (A[mid] > A[mid - 1]) {
start = mid;
} else {
end = mid;
}
}
return A[start] > A[end] ? start : end;
}
}