Skip to content

Commit d500314

Browse files
author
weiy
committed
find minimum in rotated sorted array medium
1 parent 97a4822 commit d500314

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""
2+
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
3+
4+
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
5+
6+
Find the minimum element.
7+
8+
You may assume no duplicate exists in the array.
9+
10+
Example 1:
11+
12+
Input: [3,4,5,1,2]
13+
Output: 1
14+
Example 2:
15+
16+
Input: [4,5,6,7,0,1,2]
17+
Output: 0
18+
19+
找旋转过的排序数组中最小的数。
20+
21+
有旋转则旋转点最小,无则 0 最小。
22+
23+
beat: 100% 20ms
24+
48% 24ms
25+
26+
测试地址:
27+
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/
28+
29+
"""
30+
class Solution(object):
31+
def find_rotate(self, nums):
32+
target = nums[0]
33+
34+
lo = 1
35+
36+
hi = len(nums)
37+
38+
while lo < hi:
39+
mid = (lo + hi) // 2
40+
if nums[mid] > target:
41+
lo = mid + 1
42+
else:
43+
hi = mid
44+
45+
return lo
46+
47+
def findMin(self, nums):
48+
"""
49+
:type nums: List[int]
50+
:rtype: int
51+
"""
52+
53+
rotate = self.find_rotate(nums)
54+
55+
if rotate == len(nums):
56+
return nums[0]
57+
58+
return nums[rotate]

0 commit comments

Comments
 (0)