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.
思路:貌似很简单,就是遍历,找到第一个即可。
#include <iostream>
#include <vector>
using namespace std;
int FindPeakElement(vector<int>& vec)
{
int i;
if(vec.size() ==1)
return 0;
for(i=0;i<vec.size();i++)
{
if(i == 0 && vec[i]>vec[i+1])
return i;
else if(i== vec.size()-1 && vec[i] > vec[i-1])
return i;
else if(vec[i]>vec[i-1]&& vec[i]> vec[i+1])
return i;
}
return -1;
}
int main()
{
int array[] ={3,4,5,6,7,3,5};
vector<int> vec(array,array+sizeof(array)/sizeof(array[0]));
cout<<FindPeakElement(vec);
system("pause");
return 0;
}