Skip to content

Commit af16a4a

Browse files
committed
#154: Find Minimum in Rotated Sorted Array II
1 parent af03921 commit af16a4a

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Suppose an array of length n sorted in ascending order is rotated between 1 and n times.
2+
# For example, the array nums = [0,1,4,4,5,6,7] might become:
3+
4+
# [4,5,6,7,0,1,4] if it was rotated 4 times.
5+
# [0,1,4,4,5,6,7] if it was rotated 7 times.
6+
# Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array
7+
# [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
8+
9+
# Given the sorted rotated array nums that may contain duplicates, return the minimum element
10+
# of this array.
11+
12+
# You must decrease the overall operation steps as much as possible.
13+
14+
15+
# Example 1:
16+
17+
# Input: nums = [1,3,5]
18+
# Output: 1
19+
# Example 2:
20+
21+
# Input: nums = [2,2,2,0,1]
22+
# Output: 0
23+
24+
25+
# Constraints:
26+
27+
# n == nums.length
28+
# 1 <= n <= 5000
29+
# -5000 <= nums[i] <= 5000
30+
31+
32+
from typing import List
33+
class Solution:
34+
def findMin(self, nums: List[int]) -> int:
35+
l = 0
36+
r = len(nums) - 1
37+
38+
while l < r:
39+
m = (l+r)//2
40+
if nums[m] == nums[r]:
41+
r -= 1
42+
elif nums[m] < nums[r]:
43+
r = m
44+
else:
45+
l += 1
46+
return nums[l]

0 commit comments

Comments
 (0)