leetcode -- Find Peak Element -- 找波峰--重点

https://leetcode.com/problems/find-peak-element/

思路就是二分查找。如果mid在波峰的递减部分,那么e = mid - 1. 如果mid在波峰的递增部分,那么s = mid + 1. 如果mid在波峰,那么返回。

my code: 效率不高。

class Solution(object):
    def findPeakElement(self, nums):
        """ :type nums: List[int] :rtype: int """
        s, e = 0, len(nums) - 1
        if len(nums) == 1: return 0
        while s <= e:
            mid = (s + e) /2
            #print (s, e, mid)
            if mid == 0 and nums[mid] > nums[mid + 1] :
                return mid
            elif mid == len(nums) - 1 and nums[mid] > nums[mid - 1] :
                return mid
            elif mid >0 and mid < len(nums) - 1 and nums[mid] > nums[mid + 1] and nums[mid] > nums[mid - 1] :
                return mid

            if nums[mid] > nums[mid + 1]:
                e = mid - 1
            else:
                s = mid + 1

        return -1

参考:http://blog.csdn.net/u010367506/article/details/41943309
http://bookshadow.com/weblog/2014/12/06/leetcode-find-peak-element/
有效率更高的方法

你可能感兴趣的:(LeetCode)