Sunday, April 12, 2015

162. Find Peak Element Leetcode Java

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.
Note:
Your solution should be in logarithmic complexity.
Solution:
The difficulty is to find the peak element in O(logn).
Since num[i]!=num[i+1], for a given middle element, num[m], there will be 4 cases:
1. num[m-1]<num[m]>num[m+1]: num[m] will be the peak element.
2. num[m-1]<num[m]<num[m+1]: there must exist a peak element in the right half. Let's think at that way, in order to make num[m+1] is not the peak element, the following must be true: num[m+1]<num[m+2]; similarly num[m+2] must < num[m+3]...so in order to make num[end-1] is not the peak element, num[end-1]< num[end], thus num[end] is the peak element, because we consider num[n]=-∞. there must exist a peak element in the right half and we can cut the left half.
3. num[m-1]>num[m]>num[m+1], similarly there must exist a peak element in the left half.
4. num[m-1]>num[m]<num[m+1], either half is OK.
When there is only 2 elements in the array, return the bigger one.
 public int findPeakElement(int[] num) {  
     if(num==null || num.length==0) return -1;  
     int l=0;  
     int r=num.length-1;  
     while(l+1<r){  
       int m=(r-l)/2+l;  
       if(num[m]>num[m+1] && num[m]>num[m-1]) return m;  
       else if(num[m]<num[m+1]) l=m+1;  
       else r=m-1;  
     }  
     return (num[l]<=num[r])? r : l;  
   }  

No comments:

Post a Comment