153. Find Minimum in Rotated Sorted Array

Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:


def findMin(nums: List[int]):
   
    if len(nums) == 1:
        return nums[0]

    left, right = 0, len(nums) - 1

    if nums[right] > nums[left]: # Still sorted
        return nums[left]

    while left <= right:
       
        mid = (left + right) // 2
       
        if nums[mid + 1] < nums[mid]:
            return nums[mid + 1]
       
        if nums[mid] < nums[mid - 1]:
            return nums[mid]
       
        # Since the list is definitely not sorted
        # as ruled out by initial condition
        # this [mid] > [0] means, lowest is to the left
        if nums[mid] > nums[0]:
            left = mid + 1
        else:
            right = mid - 1
    assert False # can't reach here    
    

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break