python leetcode 153. Find Minimum in Rotated Sorted Array 154. Find Minimum in Rotated Sorted Array

典型的旋转排序数组中的二分查找。这道题降低了难度,没有重复元素。自己做的时候可以考虑如果有重复元素该如何?

153. Find Minimum in Rotated Sorted Array

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

154. Find Minimum in Rotated Sorted Array

class Solution(object):
    def findMin(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return -1 
        ln = len(nums)
        if ln<=2:
            return min(nums)
        i=0
        j=ln-1
        while i<j-1:
            if nums[i] < nums[j]:
                return nums[i]
            mid=(i+j)>>1
            if nums[mid]<nums[i]:
                j=mid 
            elif nums[mid]>nums[j]:
                i=mid 
            else:
                i+=1 
        return min(nums[i],nums[j])

你可能感兴趣的:(leetcode,python,python,leetcode)