Leetcode 162 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.

click to show spoilers.

Note:

Your solution should be in logarithmic complexity.

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

 

题目解析:

因为要求logarithmic complexity, 所以一看就是用二分的思想来做. 两个mid index

 

 1 public int findPeakElement(int[] num) {
 2         int start = 0;
 3         int end = num.length - 1;
 4         while(start != end){
 5             int mid1 = start + (end - start) / 2;
 6             int mid2 = mid1 + 1;
 7             if(num[mid1] < num[mid2]){
 8                 start = mid2;
 9             }else
10                 end = mid1;
11         }
12         return start;
13 }

 

posted @ 2015-02-16 22:20  Sherry是小太阳  阅读(105)  评论(0编辑  收藏  举报