leetcode 154

153的进阶版, 原列表不是严格递增的, 相似, 增加更多的边界判断就可以, 但是极端情况下, 也就是列表中重复的数字过多可能会到O(n)的复杂度.

class Solution:
    def findMinInRange(self, nums: List[int], start, end) -> int:
        if start == end:
            return nums[start]
        if nums[start] < nums[end]:
            return nums[start]
        elif nums[start] == nums[end]:
            mid = (start + end) // 2
            tmp = self.findMinInRange(nums, start, mid)
            if tmp < nums[start]:
                return tmp
            return self.findMinInRange(nums, mid+1, end)
        while start < end:
            mid = (start + end) // 2
            if nums[start] > nums[mid]:
                end = mid
                continue
            elif nums[start] == nums[mid]:
                if start == mid:
                    return min(nums[start], nums[end])
                start = mid
                continue
            else:
                start = mid
                continue
                
    def findMin(self, nums: List[int]) -> int:
        len_nums = len(nums)
        result = self.findMinInRange(nums, 0, len_nums-1)
        return result
posted @ 2021-11-21 19:01  茫茫碧落  阅读(43)  评论(0编辑  收藏  举报