1、题目
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.
Your solution should be in logarithmic complexity.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
2、分析:
采用依次遍历法,显然很容易解决此问题,但题目中要求“logarithmic complexity”,而一次遍历法的时间复杂度为O(n)。因此,必须用其它方法;由“logarithmic complexity”我们容易联想到用二分法。
但怎么使用二分法,我一开始并没想到,看了http://blog.csdn.net/u012162613/article/details/41791715,我才想到。
其实质为:对于任意序列,其A[start] > A[strat - 1],A[end] > A[end + 1];因此若A[mid] < A[mid - 1],则A[0]~A[mid - 1]存在Peak。因为若A[0] ~ A[mid- 1]单调递增,则A[mid - 1]为Peak;若A[0] ~ A[mid- 1]单调递减,则A[0]为Peak。若不具有单调性,则对A[0]~A[mid-1]进行分割。
3、代码:
class Solution {
public:
int findPeakElement(const vector<int> &num) {
return findPeakElement(num,0,num.size() - 1);
}
private:
int findPeakElement(const vector<int> &num,int start,int end){
if((end - start) <= 1){
return num[start] > num[end] ? start : end;
}
int mid = (start + end)/2;
if(num[mid] < num[mid - 1] ){
return findPeakElement(num,start,mid - 1);
}else if(num[mid] < num[mid + 1]){
return findPeakElement(num,mid + 1,end);
}else
return mid;
}
};