LeetCode笔记

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

2018-04-25  本文已影响34人  只为此心无垠

Leetcode题目地址

    def findMin(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
#         这个版本只适用于旋转数组,并不适合正常升序的数组
#         if len(nums) <= 0:
#             return -1
        
#         start = 0
#         end = len(nums) -1
        
#         while start + 1 < end:
#             mid = (start + end) /2
#             if nums[mid] > nums[start]:# 左边
#                 start = mid
#             else:
#                 end = mid
                
#         return min(nums[start],nums[end])
             
        if len(nums) == 0:
            return 0

        start, end = 0, len(nums) - 1
        while start + 1 < end:
            mid = (start + end) / 2
#mid落在后半段,把后半段去了
            if nums[mid] <= nums[-1]:#需要使用end的那个数来判断,来兼容正常和旋转  因为后半段和正常的升序一致
                end = mid
#mid落在前半段,把前半段去了
            else:
                start = mid
        return min(nums[start], nums[end])

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

def findMin(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return 0
#             但是因为有重复元素的存在,所以最坏情况下复杂度是O(n),当num[mid]>num[r]的时候,可以肯定,最小值肯定在[mid,r]之间,当num[mid]<num[l]时,可以肯定,最小值肯定在[l,mid]之间,否则的话,num[l]=num[mid]=num[r]的情况下,两个区间都有可能
        start, end = 0, len(nums) - 1
        
        while start  < end:
            mid = (start + end) / 2
            if nums[mid] < nums[end]:
                end = mid
            elif nums[mid] > nums[end]:
                start = mid+1
            else:
                end = end -1
        return nums[start]

解法二:

def findMin(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return 0

        start, end = 0, len(nums) - 1
        
        while start+1  < end:
            mid = (start + end) / 2
            if nums[mid] < nums[end]:#mid在后半段
                end = mid
            elif nums[mid] > nums[end]:#mid在前半段
                start = mid
            else:#mid在哪里都有可能
                end = end -1
        return min(nums[start],nums[end])
        

上一篇 下一篇

猜你喜欢

热点阅读