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 1
1
'''
2
2
# 153. Find Minimum in Rotated Sorted Array
3
3
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.
9
11
'''
10
12
class 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 :
12
19
if len (nums ) == 1 :
13
20
return nums [0 ]
14
21
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