File tree Expand file tree Collapse file tree 1 file changed +21
-18
lines changed
search-in-rotated-sorted-array Expand file tree Collapse file tree 1 file changed +21
-18
lines changed Original file line number Diff line number Diff line change 1- # TC : O(n) - Where it takes the length n of input list
2- # SC : O(1) - Only a few extra variables are used regardless of input size
3- class Solution :
4- def findMin (self , nums : List [int ]) -> int :
5- for i in range (len (nums ) - 1 ):
6- if nums [i ] > nums [i + 1 ]:
7- return nums [i + 1 ]
8- return nums [0 ]
1+ # O(log n)
2+ # O(1)
93
104
11- # TC: O(log(n)) - The search space is halved each round until the minimum is found
12- # SC: O(1) - Only a few extra variables are used regardless of input size
135class Solution :
14- def findMin (self , nums : List [int ]) -> int :
15- low , high = 0 , len (nums ) - 1
6+ def search (self , nums : List [int ], target : int ) -> int :
7+ left , right = 0 , len (nums ) - 1
8+
9+ while left <= right :
10+ mid = (left + right ) // 2
1611
17- while low < high :
18- mid = ( high + low ) // 2
12+ if nums [ mid ] == target :
13+ return mid
1914
20- if nums [mid ] > nums [high ]:
21- low = mid + 1
15+ # Check if left half is sorted
16+ if nums [left ] <= nums [mid ]:
17+ if nums [left ] <= target < nums [mid ]:
18+ right = mid - 1
19+ else :
20+ left = mid + 1
21+ # Otherwise, right half is sorted
2222 else :
23- high = mid
23+ if nums [mid ] < target <= nums [right ]:
24+ left = mid + 1
25+ else :
26+ right = mid - 1
2427
25- return nums [ low ]
28+ return - 1
You can’t perform that action at this time.
0 commit comments