a peak element is a element is greater than its neighbors.
given an input array where num[i]≠num[i+1], the find a peak element and return its index.
you may imagine this num[-1] = num[n] =-∞.
for example, in array [1, 2, 3, 1], 3 is a peak eleme NT and your function should return the index number 2.
note:
your solution should is in logarithmic Complexity.
This topic requires a time complexity of O (log (N)), can use binary lookup to do, but the update search interval here is not quite the same: if the previous step to mid is uphill and mid's next is downhill, then mid is the peak; if the previous and the last steps of mid are uphill, Then the top of the mountain must be in the second half of the range; if the previous and next steps of mid are downhill, the peak must be in the first half. In addition, boundary issues need to be addressed.
My C + + code is implemented as follows:
int findpeakelement (const vector<int> &num) { int low = 0, high = num.size ()-1; while (low <= high) { int mid = (low + high) >> 1; BOOL Isuphillforward = (Mid = = 0? True:num[mid] > Num[mid-1]); BOOL Isuphillafter = (Mid = = Num.size ()-1? false:num[mid + 1] > Num[mid]); if (Isuphillforward &&!isuphillafter) return mid; else if (Isuphillforward && isuphillafter) Low = mid + 1; else high = mid-1; } return low;}
Leetcode[array]: Find Peak Element