Find Peak Element
A peak element is an element that is greater than its neighbors.
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] = -∞
.
For example, in array [1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
public class Solution { public int findPeakElement(int[] num) { return find(num,0,num.length-1); } int find(int[] A, int l, int r){ while(l<r){ int center=(l+r)/2; if(center==l&¢er+1<=r&&A[center+1] <= A[center]||center==r-1&¢er-1>l&&A[center-1]<=A[center]|| center>l&¢er<r&&A[center-1] <= A[center]&&A[center+1] <= A[center]){ return center; }else if(center>l&&A[center]<A[center-1]){ return find(A,l,center-1); }else{ return find(A,center+1,r); } } return l; } }
自己的个人博客:bingtel-木犹如此的博客 , 有兴趣可以关注下