A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1]
, find a peak element and return its index.
You may imagine that num[-1] = num[n] = -∞
.
For example, in array [1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.
public int findPeakElement(int[] num) {
return find(num, 0, num.length-1);
}
public int find(int[] num, int start, int end) {
int mid = (start + end)/2;
if ( (mid == 0 || num[mid] > num[mid-1]) && (mid == num.length-1 || num[mid] > num[mid+1])) return mid;
else if (mid > 0 && num[mid-1] > num[mid]) return find(num, start, mid-1);
else return find(num, mid + 1, end);
}