Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7]
might become [4,5,6,7,0,1,2]
).
Find the minimum element.
You may assume no duplicate exists in the array.
Example 1:
Input: [3,4,5,1,2]
Output: 1
Example 2:
Input: [4,5,6,7,0,1,2]
Output: 0
LeetCode:链接
LeetCode变体:LeetCode154:Find Minimum in Rotated Sorted Array II
和 剑指Offer_编程题06:旋转数组的最小数字(指针)思路是一样的。这题因为没有重复数字,所以比剑指offer的题要简单一点。但是边界问题我实在是弄不清楚,所以就和剑指offer的题用了同样的代码。
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return None
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] > nums[high]:
low = mid + 1
elif nums[mid] < nums[high]:
high = mid
else:
high -= 1
return nums[low]