Tuesday, November 17, 2015

leetcode: Find Peak Element

Difficulty: Medium
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide Tags
 Array Binary Search















-----------------------------------

Note the condition: num[-1] = num[n] = -∞

So the turning condition is that:
when num[mid]>num[mid-1], turn right, L=mid+1;
when num[mid]<num[mid+1], turn right, r=mid;

See examples:

(How about this input: [-2147483648,-2147483647] ??)

/////////////////////////////////////////////////////
//codes
 class Solution {
 public:
int findPeakElement(const vector<int> &num) {
int n = num.size();
//check input
//if(n==1)return 0;
int l = 0, r = n - 1, mid = l + (r - l) / 2;
while (r>l){
mid = l + (r - l) / 2;
if (num[mid]>num[mid - 1] && num[mid]>num[mid + 1])return mid;
else if (num[mid]>num[mid - 1]) l = mid + 1;
else r = mid;
}
return r;
}
 };








































No comments:

Post a Comment