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.
The simplest way to calculate the peak value of an array is to scan the array, judging if the median > Left value && median value > Right value , then we can get to that index value. The time complexity of the algorithm is O (n) and the code is as follows:
public class Solution {public int findpeakelement (int[] num) { if (num.length== 1 ) { return 0; } else if (Num.length ==2) { return (num[0] > num[1]? 0:1); } else{for (int i = 1;i<num.length-1;i++) { if (Num[i] > Num[i-1] && num[i] > num[i+1]) { return i; } } Return (Num[num.length-1] > num[0]? (num.length-1): 0);}}}
We try to solve this problem by dichotomy, with three numbers no more than four cases, ascending, descending, convex, concave.
public class Solution {public int findpeakelement (int[] num) {return binarysearckpeakelement (0,num.length-1,n UM); } public int binarysearckpeakelement (int left,int right,int[]num) {int mid = (right + left)/2; int value = Num[mid]; if (Right-left = = 0) {return left; } if (Right-left ==1) {return (Num[left] > num[right]? left:right); } if (Value > Num[mid-1] && value > num[mid+1]) {return mid; }else if (num[mid+1] > Num[mid-1]) {//in ascending order return binarysearckpeakelement (Mid,right,num); }else if (num[mid+1] < num[mid-1]) {//descending order return binarysearckpeakelement (Left,mid,num); }else{return binarysearckpeakelement (Left,mid,num); Binarysearckpeakelement (Mid,right,num); }} public static void Main () {Solution obj = new solution (); int []num = {12,324,54,13,43,2111,1}; int index = obj.fiNdpeakelement (num); SYSTEM.OUT.PRINTLN (index); }}
Time Complexity of O (NLOGN)
Find the Peak value