Leetcode-Find Peak Element

LiBlog發表於2014-12-10

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.

click to show spoilers.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Analysis:

binary search. Three pointers:start,mid,end.

if A[mid]<A[start/end] then exsits peak on the side start/end.

if A[mid]> both, then if A[mid]<A[mid-1], then on the side of start, otherwise, on the side of end.

Solution:

 1 public class Solution {
 2     public int findPeakElement(int[] num) {
 3         if (num.length==0) return -1;
 4 
 5         int start = 0, end = num.length-1;
 6         while ( (end-start)>1 ){
 7             int mid = (start+end)/2;
 8             if (num[mid]>num[mid-1] && num[mid]>num[mid+1]) return mid;
 9 
10             if (num[mid]<num[start]){
11                 end = mid-1;
12                 continue;
13             }
14 
15             if (num[mid]<num[end]){
16                 start = mid+1;
17                 continue;
18             }
19 
20             if (num[mid]<num[mid-1]){
21                 end = mid-1;
22                 continue;
23             } else {
24                 start = mid+1;
25                 continue;
26             }
27         }
28 
29         if (start==end) return start;
30 
31         if (num[start]>num[end]) return start;
32         else return end;            
33         
34     }
35 }

 

相關文章