Skip to content

Commit 99e158b

Browse files
committed
旋转数组最小值[有/无重复元素](二分搜索, 注意边界确定)
1 parent 5139d52 commit 99e158b

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# coding: utf8
2+
3+
4+
"""
5+
题目链接: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description.
6+
题目描述:
7+
8+
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
9+
10+
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
11+
12+
Find the minimum element.
13+
14+
You may assume no duplicate exists in the array.
15+
16+
"""
17+
18+
19+
class Solution(object):
20+
def findMin(self, nums):
21+
"""
22+
:type nums: List[int]
23+
:rtype: int
24+
"""
25+
# return self.binary_search_recursive(nums, 0, len(nums) - 1)
26+
return self.binary_search_iterative(nums, 0, len(nums) - 1)
27+
28+
def binary_search_recursive(self, nums, l, r):
29+
if l > r:
30+
return nums[r]
31+
32+
mid = l + (r - l) // 2
33+
if nums[mid] < nums[r]:
34+
return min(nums[mid], self.binary_search_recursive(nums, l, mid - 1))
35+
36+
return min(nums[l], self.binary_search_recursive(nums, mid + 1, r))
37+
38+
def binary_search_iterative(self, nums, l, r):
39+
while l <= r:
40+
mid = l + (r - l) // 2
41+
if nums[mid] < nums[r]:
42+
r = mid
43+
else:
44+
l = mid + 1
45+
46+
return nums[r]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# coding: utf8
2+
3+
4+
"""
5+
题目链接: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/description.
6+
题目描述:
7+
8+
Follow up for "Find Minimum in Rotated Sorted Array":
9+
What if duplicates are allowed?
10+
11+
Would this affect the run-time complexity? How and why?
12+
13+
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
14+
15+
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
16+
17+
Find the minimum element.
18+
19+
The array may contain duplicates.
20+
21+
"""
22+
23+
24+
class Solution(object):
25+
def findMin(self, nums):
26+
"""
27+
:type nums: List[int]
28+
:rtype: int
29+
"""
30+
left, right = 0, len(nums) - 1
31+
while left <= right:
32+
mid = left + (right - left) // 2
33+
if nums[mid] < nums[right]:
34+
right = mid
35+
elif nums[mid] > nums[right]:
36+
left = mid + 1
37+
else:
38+
right -= 1
39+
40+
return nums[right + 1]

0 commit comments

Comments
 (0)