leetcode------Find Peak Element

标题: Find Peak Element
通过率: 32.3%
难度: 中等

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.

 本题思路确实比较清楚,但是想起来不容易,要充分看到给定的条件:

1、不存在相邻相等的元素,

2、默认位置为-1和n的元素的值为负无穷,

这两个条件意思是,不用去考虑相等元素。由于可能存在多个peak值,只用找到该数组中元素最大值即可,然后就是第0个位置和最后一个元素也再考虑范围内,不用单独考虑。

整体思路就是二分法查找,在处理mid时比较下mid与mid+1的关系,看是否是递增还是递减。

java代码如下:

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

2、python:

 1 class Solution:
 2     # @param num, a list of integer
 3     # @return an integer
 4 
 5     def findPeakElement(self, num):
 6         n = len(num)
 7         left, right = 0, len(num) - 1
 8         while left < right:
 9             mid = (left + right) >> 1
10             if (mid == 0 or num[mid] > num[mid - 1]) and (mid == n - 1 or num[mid] > num[mid + 1]):
11                 return mid
12             if mid > 0 and num[mid - 1] > num[mid]:
13                 right = mid - 1
14             else:
15                 left = mid + 1
16         return left

 

posted @ 2015-02-10 11:33  pku_smile  阅读(245)  评论(0编辑  收藏  举报