154寻找旋转排序数组中的最小值II

题目:

法一:自己的代码

思路:同153一样,只不过如果遇到相等的,先缩小范围直到不相等,

from typing import List
class Solution:
    def findMin(self, nums: List[int]) -> int:
        left = 0
        right = len(nums) - 1
        res = float('inf')
        while left < right:
            mid = (left + right) >> 1
            if nums[left] == nums[right]:
                left = left + 1
            elif nums[mid] == nums[right]:
                right = right - 1
                res = min(nums[mid], res)
            elif nums[mid] == nums[left]:
                left = left + 1
                res = min(nums[mid], res)
            else:
                if nums[right] < nums[left]:
                    if nums[mid] < nums[right]:
                        res = min(nums[mid], res)
                        right = mid
                    else:
                        res = min(nums[right], res)
                        left = mid + 1
                else:
                    res = min(nums[left], res)
                    right = mid
        return min(res, nums[left])
if __name__ == '__main__':
    solution = Solution()
    # result = solution.findMin([4,5,6,7,0,1,2])
    # result = solution.findMin([2,2,2,0,1])
    # result = solution.findMin([2,0,1,1,1])
    result = solution.findMin([1,2,2,2,0,1,1])
    print(result)
View Code

改进后的代码:

思路:同153改进后的一样,仍然是用中间端点和右边端点的关系进行讨论,只不过多加了对相等情况的处理,

class Solution:
    def findMin(self, nums: List[int]) -> int:
        left, right = 0, len(nums) - 1
        while left < right:
            mid = (left + right) // 2
            if nums[mid] > nums[right]: left = mid + 1
            elif nums[mid] < nums[right]: right = mid
            else: right = right - 1 # key
        return nums[left]


作者:jyd
链接:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii/solution/154-find-minimum-in-rotated-sorted-array-ii-by-jyd/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
View Code

ttt

 

posted on 2020-02-24 20:10  吃我一枪  阅读(149)  评论(0编辑  收藏  举报

导航