162. Find Peak Element

这道题快到让我怀疑自我,代码如下:

class Solution(object):
    def findPeakElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return -1
        if len(nums) == 1:
            return 0
        for i in range(len(nums)):
            if i == 0 and nums[i+1] < nums[i]:
                return i
            elif i == len(nums) - 1 and nums[i] > nums[i-1]:
                return i
            else:
                if nums[i] > nums[i-1] and nums[i] > nums[i+1]:
                    return i

当然是要怀疑自我的,因为最好的办法还是二分查找呀,代码如下:

class Solution(object):
    def findPeakElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return -1
        if len(nums) == 1:
            return 0
        left = 0 
        right = len(nums) - 1
        while left < right:
            mid = (left + right) / 2
            if nums[mid] < nums[mid+1]:
                left = mid + 1
            else:
                right = mid
        return left

你可能感兴趣的:(162. Find Peak Element)