Skip to content

Commit 3376772

Browse files
Chris WuChris Wu
Chris Wu
authored and
Chris Wu
committed
find-minimum-in-rotated-array
1 parent 990d17d commit 3376772

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
If you have not see the [explaination](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/356286/Best-Python-Solution-(How-to-Solve-all-Similar-Problem-Explained)) of the previous [question](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/), please see it first.
3+
This problem has duplicate value in compare to the previous.
4+
The difference is that when you cut the rotated array into half, there might not be a sorted array occur.
5+
You might have something like `[2,2,2,2,1,2,2,2,2,2,2]`.
6+
If we can't find either left-half or right-half is sorted, we simply reduce the range (`l = l+1, r = r-1`) and use the same method again.
7+
"""
8+
class Solution(object):
9+
def findMin(self, nums):
10+
if nums is None or len(nums)==0:
11+
return None
12+
m = nums[0]
13+
l = 0
14+
r = len(nums)-1
15+
16+
while l<=r:
17+
p = (l+r)/2
18+
m = min(m, nums[l], nums[p], nums[r])
19+
20+
if nums[l]<nums[r]:
21+
break
22+
elif nums[l]<nums[p]:
23+
l = p+1
24+
elif nums[p]<nums[r]:
25+
r = p-1
26+
else:
27+
l = l+1
28+
r = r-1
29+
return m
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
We use `m` to keep track of the min.
3+
The idea is simple, cut the rotated array into half.
4+
One part must be sorted, the other half might or might not be sorted.
5+
In the sorted parted the smallest one is the first element.
6+
In the other part we continue to the same method until it is sorted.
7+
"""
8+
class Solution(object):
9+
def findMin(self, nums):
10+
if nums is None or len(nums)==0: return None
11+
m = nums[0]
12+
l = 0
13+
r = len(nums)-1
14+
15+
while l<=r:
16+
p = (l+r)/2
17+
m = min(m, nums[l], nums[p], nums[r])
18+
19+
if nums[l]<nums[r]:
20+
#the l~r is sorted now
21+
#the smallest is at `l`, and we compared it already.
22+
break
23+
else:
24+
if nums[l]<nums[p]:
25+
#l~p is sorted
26+
#the smallest is at `l`, and we compared it already.
27+
#use the same method on (p+1)~r
28+
l = p+1
29+
elif nums[p]<nums[r]:
30+
#p~r is sorted
31+
#the smallest is at `l`, and we compared it already.
32+
#use the same method on l~(p-1)
33+
r = p-1
34+
else:
35+
break
36+
return m

0 commit comments

Comments
 (0)