Find Peak Element
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.
I write my own a bit less, this problem to be used to find two points to achieve. But I never understood why it was possible to use binary search to achieve
1 Public classSolution {2 Public intFindpeakelement (int[] num) {3 if(Num.length = = 0 | | num.length = = 1)4 return0;5 BooleanISINCR =false;//is ascending6 intindex =-1;//Peak Index value7 intNumarray[] =New int[Num.length + 2];8 for(inti = 0; I < num.length;i++){9Numarray[i + 1] =Num[i];Ten } OneNumarray[0] =Integer.min_value; ANUMARRAY[NUMARRAY.LENGTH-1] =Integer.min_value; - - for(inti = 1; I < numarray.length;i++){ the if(Numarray[i] > Numarray[i-1]) -ISINCR =true; - if(ISINCR && Numarray[i] < numarray[i-1]){ -index = i-2; + Break; - } + } A at returnindex; - } -}
The following is Baidu to, as if it is csdn or where, I am too lazy to find the source of origin. This time complexity is O (N)
1 Public classSolution {2 Public intFindpeakelement (int[] num) {3 for(inti = 1; i < num.length; i++){4 if(Num[i] < num[i-1])5 returnI-1;6 }7 returnNum.length-1;8 }9}
Here is the discussion area with a binary search implementation
1 Public classSolution {2 Public intFindpeakelement (int[] num) {3 intLow = 0;4 intHigh = Num.length-1;5 while(Low <High ) {6 intMid = (low + high + 1)/2;7 if(Mid = = 0 | | num[mid] > NUM[MID-1]) {8Low =mid;9}Else {TenHigh = Mid-1; One } A } - returnLow ; - } the}
Find Peak Element