美文网首页
162. Find Peak Element

162. Find Peak Element

作者: April63 | 来源:发表于2018-05-15 14:26 被阅读0次

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

    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

          本文链接:https://www.haomeiwen.com/subject/isnedftx.html