There is a integer array which has the following features:
- The numbers in adjacent positions is different.
- A[0] < a[1] && a[a.length-2] > a[a.length-1].
We define a position P is a peek if:
A[P] > A[P-1] && A[P] > A[P+1]
Find a peak element in the this array. Return the index of the peak.
Notice
The array may contains multiple peeks, find any of the them.
Has you met this question in a real interview?
Example
Given[1, 2, 1, 3, 4, 5, 7, 6]
Return index 1
(which is number 2) or 6
(which is number 7)
Challenge
Time complexity O (LOGN)
For the original question on Leetcode, please see my previous blog find Peak Element.
Solution One:
classSolution { Public: /** * @param a:an integers array. * @return: Return any of peek positions. */ intFindpeak (vector<int>A) {intleft =0, right = A.size ()-1; while(Left <Right ) { intMid = left + (right-left)/2; if(A[mid] < A[mid +1]) left = mid +1; Elseright =mid; } returnRight ; }};
Solution Two:
classSolution { Public: /** * @param a:an integers array. * @return: Return any of peek positions. */ intFindpeak (vector<int>A) { for(inti =1; I < a.size (); ++i) {if(A[i] < a[i-1])returnI1; } returnA.size ()-1; }};
[Lintcode] Find Peak Element to find the peaks of an array