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.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
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.
Approach: Use binary search.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | int peakIndex(int *arr, int low, int high){ if(low == high){ return low; } if(low + 1 == high){ if(arr[low] >= arr[high]){ return low; }else{ return high; } } int mid = (low + high) / 2; if(arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]){ return mid; }else if(arr[mid] < arr[mid - 1]){ //peak lies on the left since arr[mid - 1] > arr[mid] && arr[0] = -infinity so there has to be an element which is peak on the left return peakIndex(arr, low, mid - 1); }else{ //peak lies on the right return peakIndex(arr, mid + 1, high); } } int findPeakElement(int* nums, int numsSize) { return peakIndex(nums, 0, numsSize - 1); } |