Find Peak Element
Problem:
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.
Ideas:
Two-point Search
My train of thought:
Public classSolution { Public intFindpeakelement (int[] num) { if(num = =NULL|| Num.length = = 0)return-1; intLen =num.length; if(len = 1 | | num[0] > NUM[1])return0; if(Num[len-1] > Num[len-2])returnLen-1; intleft = 1; intright = Len-2; returngetpeakindex (num, left, right); } Public intGetpeakindex (int[] num,intLeftintRight ) { if(Left > right)return-1; if(left = =Right ) { if(Num[left] > Num[left-1] && num[left] > num[left + 1])returnLeft ; Else return-1; } intMid = (left + right)/2; if(Num[mid] > Num[mid-1] && num[mid] > num[mid + 1])returnmid; intindex = Getpeakindex (num, left, mid-1); if(Index = =-1) Index= Getpeakindex (num, mid + 1, right); returnindex; } }
View Code
Improved post-algorithm:
Public classSolution { Public intFindpeakelement (int[] num) { if(num = =NULL|| Num.length = = 0)return-1; intLen =num.length; if(len = = 1)return0; intleft = 0; intright = Len-1; while(Left <=Right ) { intMid = (left + right)/2; if(Mid = = 0) { if(Num[mid] > Num[mid+1])returnmid; } Else if(Mid = = Len-1) { if(Num[mid] > Num[mid-1])returnmid; } Else { if(Num[mid] > Num[mid-1] && num[mid] > num[mid+1])returnmid; } if(Num[mid] < num[mid+1]) left = mid + 1; Elseright =mid; } return-1; }}
View Code
Others code:
classSolution { Public: intFindpeakelement (Constvector<int> &num) { intLeft=0,right=num.size ()-1; while(left<=Right ) { if(left==Right )returnLeft ; intMid= (left+right)/2; if(num[mid]<num[mid+1]) left=mid+1; Else Right=mid; } }};
View Code
The Learning Place:
- First of all there must be peak points, because the leftmost num[-1]=num[n]= negative infinity, there must be a peak
- If the middle point is not peak, move towards the left and right sides of the rising
- Left and right, are going up the place to go, meet the place is peak point (this is a bit difficult to understand AH), did not prove it, but a thought is such a thing
- Because the peak point is definitely there, right = mid does not cause a dead loop and always jumps out of the loop.
Find Peak Element