File tree Expand file tree Collapse file tree 1 file changed +33
-7
lines changed
find-minimum-in-rotated-sorted-array Expand file tree Collapse file tree 1 file changed +33
-7
lines changed Original file line number Diff line number Diff line change 11'''
22# 153. Find Minimum in Rotated Sorted Array
33
4- ## Time Complexity: O(n)
5- - min() iterates through all elements to find the smallest one.
6-
7- ## Space Complexity: O(1)
8- - no extra space is used.
4+ > **why binary search works in a "rotated" sorted array?**
5+ > rotated sorted array consists of **two sorted subarrays**, and the minimum value is the second sorted subarray's first element.
6+ > so 👉 find the point that second sorted subarray starts.
7+ >
8+ > - if nums[mid] > nums[right]? => the pivot point is in the right half.
9+ > - if nums[mid] <= nums[right]? => the pivot point is in the left half.
10+ > - loop until left and right are the same.
911'''
1012class Solution :
11- def findMin (self , nums : List [int ]) -> int :
13+ '''
14+ ## A. brute force(not a solution)
15+ - TC: O(n)
16+ - SC: O(1)
17+ '''
18+ def findMinBF (self , nums : List [int ]) -> int :
1219 if len (nums ) == 1 :
1320 return nums [0 ]
1421
15- return min (nums )
22+ return min (nums ) # check all elements
23+
24+ '''
25+ ## B. binary search
26+ - TC: O(log n)
27+ - SC: O(1)
28+ '''
29+ def findMinBS (self , nums : List [int ]) -> int :
30+ left = 0
31+ right = len (nums ) - 1
32+
33+ while left < right :
34+ mid = (left + right ) // 2
35+
36+ if nums [mid ] > nums [right ]:
37+ left = mid + 1
38+ else :
39+ right = mid
40+
41+ return nums [left ]
You can’t perform that action at this time.
0 commit comments