题目
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
请找出其中最小的元素。
注意数组中可能存在重复的元素。
链接:https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/submissions/
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.
The array may contain duplicates.
Example:
Input: [2,2,2,0,1]
Output: 0
思路及代码
二分查找
- 基本和Leetcode-153. 寻找旋转排序数组中的最小值一样,唯一的区别是重复值
- 遇到重复值时,将high向左移动一位,然后继续查找即可
class Solution:
def findMin(self, nums: List[int]) -> int:
low = 0
high = len(nums) - 1
while low < high:
mid = int((low+high) / 2)
if nums[mid] == nums[high]:
high -= 1
elif nums[mid] < nums[high]:
high = mid
else:
low = mid + 1
return nums[high]
复杂度
T = O ( l o g n ) O(logn) O(logn)