【python3】leetcode 153. Find Minimum in Rotated Sorted Array(Medium)

153. Find Minimum in Rotated Sorted Array(Medium)

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]).

Find the minimum element.

You may assume no duplicate exists in the array.

Example 1:

Input: [3,4,5,1,2] 
Output: 1

Example 2:

Input: [4,5,6,7,0,1,2]
Output: 0

1 顺序扫描

class Solution:
    def findMin(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
    
        #-----sequencial scan------O(N)
        for i in range(len(nums)-1):
            if nums[i+1] < nums[i]:return nums[i+1]
        return nums[0]

2 binary search

 

这个二分比较有意思 因为mid的比较条件是和首尾比较来判断是往左走还是往右走

【python3】leetcode 153. Find Minimum in Rotated Sorted Array(Medium)_第1张图片

如果nums[mid] > nums[-1]  往右走,lo = mid + 1

如果nums[mid] < nums[0] 往左走,hi = mid - 1

那么遇到最小值时的等号放哪里? 因为最小值一定是属于旋转后的右半部分的,所以min > nums[-1]不成立,min < nums[0]成立,所以hi--,退出循环,这时候lo才是最小值的位置

class Solution:
    def findMin(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        #------binary search-------O(log(N))
        if nums[0] < nums[-1]:return nums[0] #no rotate
        lo = 0;hi = len(nums)-1
        while(lo <= hi):
            mid = (lo + hi)// 2
            if nums[mid] > nums[-1]:
                lo = mid + 1
            elif nums[mid] <= nums[0]:
                hi = mid - 1
        return nums[lo]
        

 

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