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.
1、顺序查找
int findPeakElement(const vector<int> &num) {
if(num.size()==1||num.at(0)>num.at(1)) return 0;
if(num.at(num.size()-1)>num.at(num.size()-2)) return num.size()-1;
int i=1;
for(;i<num.size()-1;i++)
{
if(num.at(i)>num.at(i-1)&&num.at(i)>num.at(i+1)) break;
}
return i;
}
2、递归查找-传值作为判断条件
int findPeakElement(const vector<int> &num) {
if(num.size()==1||num.at(0)>num.at(1)) return 0;
if(num.at(num.size()-1)>num.at(num.size()-2)) return num.size()-1;
bool isFind=false;
int index=-1;
findPeak(num,1,num.size()-2,isFind,index);
return index;
}
void findPeak(const vector<int> &num,int low,int high,bool &isFind,int &index)
{
if(low>high||isFind) return;
int mid=(low+high)/2;
if(isPeak(mid,num))
{
isFind=true;
index=mid;
return;
}
findPeak(num,low,mid-1,isFind,index);
findPeak(num,mid+1,high,isFind,index);
}
bool isPeak(int &index,const vector<int> &num)
{
if(num.at(index)>num.at(index-1)&&num.at(index)>num.at(index+1)) return true;
return false;
}
3、二分查找-分析该题的特征,在mid处判断num.at(mid)与num.at(mid+1)大小,假使num.at(mid+1)较大:
a、mid+2~high单调递增,则high为peak;
b、非单调递增,必定出现一个较左边邻居小的数,此时也可查找peak;
int findPeakElement(const vector<int> &num) {
if(num.size()==1) return 0;
int low=0;
int high=num.size()-1;
int mid=0;
while(low<high)
{
mid=(low+high)/2;
if(num.at(mid)>num.at(mid+1))
{
high=mid;
}
else
{
low=mid+1;
}
}
return low;
}