153. Find Minimum in Rotated Sorted Array

2021. 10. 27. 21:20Leetcode

Description:

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:

  • [4,5,6,7,0,1,2] if it was rotated 4 times.
  • [0,1,2,4,5,6,7] if it was rotated 7 times.

Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].

Given the sorted rotated array nums of unique elements, return the minimum element of this array.

You must write an algorithm that runs in O(log n) time.

'''
[1] Binary search)

idea::
find mid point, and if mid_val > right.val then, min will lie on right-part, else min will lie on left-part

-T/C: O(logn)
-S/C: O(1)
'''

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

'Leetcode' 카테고리의 다른 글

222. Count Complete Tree Nodes  (0) 2021.10.28
1. Two Sum  (0) 2021.10.28
162. Find Peak Element  (0) 2021.10.27
75. Sort Colors  (0) 2021.10.27
234. Palindrome Linked List  (0) 2021.10.27