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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Hide TagsArray Binary SearchAnalysis: Refer to http://www.cnblogs.com/diegodu/p/4589781.html This is to find the local minimum
The problem is to find the local maximum
classSolution { Public: intFindpeakelement (vector<int>&nums) { if(nums.size () = =0) return-1; if(nums.size () = =1) return 0; if(nums[0] > nums[1]) return 0; intSize =nums.size (); if(Nums[size-1] > Nums[size-2]) returnSize-1; intLow =1; intHigh = size-2; intmid; while(Low <High ) {Mid= (low + high)/2; if(Nums[mid] < nums[mid+1]) { low= mid+1; } Else if(Nums[mid] < nums[mid-1]) { high= mid-1; } Else returnmid; } returnLow ; }};
[Leetcode] Find Peak Element