LeetCode 题解工作台
寻找旋转排序数组中的最小值 II
已知一个长度为 n 的数组,预先按照升序排列,经由 1 到 n 次 旋转 后,得到输入数组。例如,原数组 nums = [0,1,4,4,5,6,7] 在变化后可能得到: 若旋转 4 次,则可以得到 [4,5,6,7,0,1,4] 若旋转 7 次,则可以得到 [0,1,4,4,5,6,7] 注意,数…
2
题型
6
代码语言
3
相关题
当前训练重点
困难 · 二分·搜索·答案·空间
答案摘要
若 `nums[mid] > nums[right]`,说明最小值在 mid 的右边;若 `nums[mid] < nums[right]`,说明最小值在 mid 的左边(包括 mid);若相等,无法判断,直接将 right 减 1。循环比较。 最后返回 `nums[left]` 即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
n 的数组,预先按照升序排列,经由 1 到 n 次 旋转 后,得到输入数组。例如,原数组 nums = [0,1,4,4,5,6,7] 在变化后可能得到:
- 若旋转
4次,则可以得到[4,5,6,7,0,1,4] - 若旋转
7次,则可以得到[0,1,4,4,5,6,7]
注意,数组 [a[0], a[1], a[2], ..., a[n-1]] 旋转一次 的结果为数组 [a[n-1], a[0], a[1], a[2], ..., a[n-2]] 。
给你一个可能存在 重复 元素值的数组 nums ,它原来是一个升序排列的数组,并按上述情形进行了多次旋转。请你找出并返回数组中的 最小元素 。
你必须尽可能减少整个过程的操作步骤。
示例 1:
输入:nums = [1,3,5] 输出:1
示例 2:
输入:nums = [2,2,2,0,1] 输出:0
提示:
n == nums.length1 <= n <= 5000-5000 <= nums[i] <= 5000nums原来是一个升序排序的数组,并进行了1至n次旋转
进阶:这道题与 寻找旋转排序数组中的最小值 类似,但 nums 可能包含重复元素。允许重复会影响算法的时间复杂度吗?会如何影响,为什么?
解题思路
方法一:二分查找
若 nums[mid] > nums[right],说明最小值在 mid 的右边;若 nums[mid] < nums[right],说明最小值在 mid 的左边(包括 mid);若相等,无法判断,直接将 right 减 1。循环比较。
最后返回 nums[left] 即可。
时间复杂度 O(logn)。
class Solution:
def findMin(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) >> 1
if nums[mid] > nums[right]:
left = mid + 1
elif nums[mid] < nums[right]:
right = mid
else:
right -= 1
return nums[left]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Tests how the candidate handles the trade-off between efficiency and correctness when dealing with duplicates in binary search.
- question_mark
Assesses the ability to modify standard algorithms (binary search) to handle edge cases, such as duplicate values and rotations.
- question_mark
Evaluates the candidate's ability to reason about the problem and identify when and why to adjust search boundaries in a rotated array.
常见陷阱
外企场景- error
Misunderstanding the handling of duplicates, leading to inefficient solutions that don't maintain the correct time complexity.
- error
Failing to recognize when the search space should be reduced due to duplicate values, causing the algorithm to behave like a linear search in the worst case.
- error
Not properly handling edge cases where the array is very small or where the array contains multiple equal elements near the pivot point.
进阶变体
外企场景- arrow_right_alt
Rotate the array more times (larger rotations), requiring better insight into how the array structure behaves after multiple rotations.
- arrow_right_alt
Use this pattern to find the maximum value instead of the minimum by reversing the logic of the binary search.
- arrow_right_alt
Implement an iterative approach rather than a recursive binary search, which might better handle larger inputs with fewer function calls.