A peak element is an element that is greater than its neighbors.java
Given an input array where num[i] ≠ num[i+1]
, find a peak element and return its index.算法
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.數組
You may imagine that num[-1] = num[n] = -∞
.code
For example, in array [1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.blog
計算一個數組的峯值,最簡單的方法就是掃描數組,判斷若是 中間值 > 左邊值 && 中間值 > 右邊值 那麼咱們就能夠獲取到該索引數值。算法的時間複雜度爲O(n),代碼以下所示:索引
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); } } }
咱們嘗試用二分法來解決這個問題,三個數無外乎四種狀況,升序排列、降序排列、凸排列,凹排列。ip
public class Solution { public int findPeakElement(int[] num) { return binarySearckPeakElement(0,num.length-1,num); } 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]){//升序排列 return binarySearckPeakElement(mid,right,num); }else if(num[mid+1] < num[mid-1]){//降序排列 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); } }
時間複雜度爲O(nlogn)element