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.
Click to show spoilers.
Note:
Your solution should is in logarithmic complexity.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
1 classSolution {2 Public:3 intFindpeakelement (vector<int>&nums) {4 if(nums.size () = =0)returnNULL;5 6 for(intI=1; I<nums.size (); i++)7 {8 if(nums[0]>nums[1])9 return 0;Ten if(Nums[nums.size ()-1]>nums[nums.size ()-2]) One returnNums.size ()-1; A if(nums[i]>nums[i-1]&&nums[i]>nums[i+1]) - returni; - the } - - returnNULL; - } +};
"Leetcode" Find Peak Element