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.

 

 

思路,用二分法寻找nums中符合条件的元素。这个条件就是local peak,也就是这个数要比左右的邻居都大。注意这个比左邻居大的条件可以用index == 0代替,因为默认nums[-1] = -infty。同理注意右端边界条件的处理。

再就是注意L16中的mid > 0和L19的mid < n。也就是说mid必须不在两头,我们才有移动left和right的需要。

 1 class Solution(object):
 2     def findPeakElement(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         
 8         n = len(nums)
 9         
10         left, right = 0, n-1
11         
12         while left <= right:
13             mid = left + (right - left)/2
14             if (mid ==0 or nums[mid]>nums[mid-1]) and (mid ==n-1 or nums[mid]>nums[mid+1]):
15                 return mid
16             elif mid >0 and nums[mid]<nums[mid-1]:
17                 right = mid-1
18             else:
19             # elif mid < n  and nums[mid]<nums[mid+1]:
20                 left = mid + 1
21         
22         return -1

 

posted @ 2017-02-06 01:33  lettuan  阅读(132)  评论(0编辑  收藏  举报