-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
solve: findMinimumInRotatedSortedArray
- Loading branch information
1 parent
f2b9477
commit b168962
Showing
1 changed file
with
22 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
# Time Complexity: O(log n) - using binary search, so cut the search space in half each time. | ||
# Space Complexity: O(1) - only use a few variables (low, high, mid), no extra space. | ||
|
||
class Solution: | ||
def findMin(self, nums: List[int]) -> int: | ||
low = 0 | ||
# start with the full range of the array | ||
high = len(nums) - 1 | ||
|
||
# find the middle index | ||
while low < high: | ||
mid = low + (high - low) // 2 | ||
|
||
# if mid is greater than the last element, the min must be on the right | ||
if nums[mid] > nums[high]: | ||
# move the low pointer to the right | ||
low = mid + 1 | ||
else: | ||
# min could be mid or in the left part | ||
high = mid | ||
# low and high converge to the minimum element | ||
return nums[low] |