【leetcode刷题笔记】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.


 

题解:题目要求用O(logn)的时间复杂度找到局部最大值,很容易想到二分算法。设置一个函数 private boolean findPeakHelper(int[] num,int begin,int end){ ,每次判断(begin+end)/2位置上的元素是否满足要求,如果不满足就搜索左半边数组,如果在左半边搜索到了,右半边就没有必要搜索了,因为题目只让返回一个解;如果左半边没搜索到,就继续递归搜索右半边。特别注意对位置0和位置n-1处元素的处理。

JAVA版本代码如下:

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

 

posted @ 2015-04-02 16:24  SunshineAtNoon  阅读(212)  评论(0编辑  收藏  举报