Skip to content

Commit fc5e5d1

Browse files
committed
feat: find-minimum-in-rotated-sorted-array
1 parent f834f08 commit fc5e5d1

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""
6+
153. 寻找旋转排序数组中的最小值
7+
https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/
8+
假设按照升序排序的数组在预先未知的某个点上进行了旋转。例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] 。
9+
请找出其中最小的元素。
10+
"""
11+
def findMin(self, nums: List[int]) -> int:
12+
m = len(nums)
13+
if m == 1:
14+
return nums[0]
15+
16+
res = nums[0]
17+
l, r = 0, m - 1
18+
while l <= r:
19+
mid = l + (r - l) // 2
20+
res = min(nums[mid], res)
21+
# 如果左侧单调
22+
if nums[l] <= nums[mid]:
23+
res = min(nums[l], res)
24+
l = mid + 1
25+
# 如果右侧单调
26+
else:
27+
res = min(nums[mid + 1], res)
28+
r = mid - 1
29+
30+
return res
31+
32+
33+
so = Solution()
34+
# print(so.findMin([3,4,5,1,2]))
35+
# print(so.findMin([4,5,6,7,0,1,2]))
36+
print(so.findMin([3, 1, 2]))

0 commit comments

Comments
 (0)