-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathfind-minimum-in-rotated-sorted-array-ii.py
40 lines (32 loc) · 1.16 KB
/
find-minimum-in-rotated-sorted-array-ii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution:
def findMin(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
while left < right:
middle = (left + right) // 2
if nums[middle] < nums[right]:
right = middle
elif nums[middle] > nums[right]:
left = middle + 1
else:
right -= 1
return nums[left]
def findMinRecursive(self, nums: List[int]) -> int:
def bisect(left, right):
if left >= right:
return nums[left]
result = float("+inf")
middle = (left + right) // 2
if nums[middle] < nums[right]:
result = min(
result, nums[middle], bisect(left, middle - 1)
)
elif nums[middle] > nums[right]:
result = min(
result, nums[middle], nums[middle + 1], bisect(middle + 1, right)
)
else:
result = min(
result, nums[middle], nums[middle - 1], bisect(left, right - 1)
)
return result
return bisect(0, len(nums) - 1)