Find Peak Element
2015.1.23 14:28
A peak element is an element, which is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1] , the find a peak element and return its index.
The array may be contain multiple peaks, in this case return the index to any one of the peaks is fine.
May imagine 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.
Note:
Your solution should is in logarithmic complexity.
Solution:
The requirement of O (log (n)) time really Got me this time (x_x) | |
I Haven ' t come by any solution with binary search. Here's one I sought out on the Internet, but judging from the run time, it seems worse to use binary search than linear s Earch. So what's the catch then?
Http://www.cnblogs.com/ganganloveu/p/4147655.html
Maybe it ' s just unreasonable to apply binary search on unordered sequences. You don ' t know for sure which path to go next, how would do it binary then? Well, I ' d say the O (log (n)) requirement is a bit unsound.
Accepted Code:
1 //1CE, 2WA, 1AC, how to achieve logn with unordered data?2 classSolution {3 Public:4 intFindpeakelement (Constvector<int> &num) {5 intn = (int) num.size ();6 7 if(n = =1) {8 return 0;9 }Ten One if(num[0] > num[1]) { A return 0; - } - the if(Num[n-1] > Num[n-2]) { - returnN-1; - } - + inti; - for(i =1; I < n-1; ++i) { + if(Num[i] > Num[i-1] && Num[i] > num[i +1]) { A returni; at } - } - } -};
Leetcode-find Peak Element