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.
C + + Implementation code:
#include <iostream>#include<vector>#include<climits>using namespacestd;classSolution { Public: intFindpeakelement (Constvector<int> &num) { if(Num.empty ())return-1; if(num.size () = =1|| num[0]>num[1]) return 0; intI=1; intn=num.size (); while(i<n-1) { if(num[i]>num[i-1]&&num[i]>num[i+1]) returni; I++; } if(i==n-1&&num[i]>num[i-1]) returni; return-1; }};intMain () {solution S; Vector<int> vec={1,2}; cout<<s.findpeakelement (VEC) <<Endl;}
Find Peak Element