LeetCode 题解工作台
搜索旋转排序数组
整数数组 nums 按升序排列,数组中的值 互不相同 。 在传递给函数之前, nums 在预先未知的某个下标 k ( 0 )上进行了 向左旋转 ,使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] …
2
题型
9
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
我们使用二分,将数组分割成 $[left,.. mid]$, $[mid + 1,.. right]$ 两部分,这时候可以发现,其中有一部分一定是有序的。 因此,我们可以根据有序的那一部分,判断 是否在这一部分中:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
整数数组 nums 按升序排列,数组中的值 互不相同 。
在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了 向左旋转,使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下标 从 0 开始 计数)。例如, [0,1,2,4,5,6,7] 下标 3 上向左旋转后可能变为 [4,5,6,7,0,1,2] 。
给你 旋转后 的数组 nums 和一个整数 target ,如果 nums 中存在这个目标值 target ,则返回它的下标,否则返回 -1 。
你必须设计一个时间复杂度为 O(log n) 的算法解决此问题。
示例 1:
输入:nums = [4,5,6,7,0,1,2], target = 0 输出:4
示例 2:
输入:nums = [4,5,6,7,0,1,2], target = 3 输出:-1
示例 3:
输入:nums = [1], target = 0 输出:-1
提示:
1 <= nums.length <= 5000-104 <= nums[i] <= 104nums中的每个值都 独一无二- 题目数据保证
nums在预先未知的某个下标上进行了旋转 -104 <= target <= 104
解题思路
方法一:二分查找
我们使用二分,将数组分割成 , 两部分,这时候可以发现,其中有一部分一定是有序的。
因此,我们可以根据有序的那一部分,判断 是否在这一部分中:
- 若 范围内的元素构成有序数组:
- 若满足 ,那么我们搜索范围可以缩小为 ;
- 否则,在 中查找;
- 若 范围内的元素构成有序数组:
- 若满足 ,那么我们搜索范围可以缩小为 ;
- 否则,在 中查找。
二分查找终止条件是 ,若结束后发现 与 不等,说明数组中不存在值为 的元素,返回 ,否则返回下标 。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def search(self, nums: List[int], target: int) -> int:
n = len(nums)
left, right = 0, n - 1
while left < right:
mid = (left + right) >> 1
if nums[0] <= nums[mid]:
if nums[0] <= target <= nums[mid]:
right = mid
else:
left = mid + 1
else:
if nums[mid] < target <= nums[n - 1]:
left = mid + 1
else:
right = mid
return left if nums[left] == target else -1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(log n) because each step halves the search space, and space complexity is O(1) if iterative, or O(log n) if recursion is used for binary search. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask why a standard binary search fails on rotated arrays.
- question_mark
Probe understanding of identifying sorted segments versus pivoted segments.
- question_mark
Check if candidate can maintain O(log n) efficiency despite rotation.
常见陷阱
外企场景- error
Attempting simple binary search without handling rotation leads to incorrect indices.
- error
Failing to correctly identify which half is sorted can skip the target unintentionally.
- error
Overlooking edge cases where the pivot is at the array start or end causes off-by-one errors.
进阶变体
外企场景- arrow_right_alt
Searching in a rotated sorted array with duplicate values requires additional checks to skip equal elements.
- arrow_right_alt
Finding the minimum element index in a rotated array leverages similar pivot detection logic.
- arrow_right_alt
Counting occurrences of a target in a rotated sorted array extends the pattern to handle multiple identical elements.