150强访谈简单

在旋转排序数组中搜索

“搜索旋转排序数组”问题的详细指南和 Python 实现。

问题陈述

简单

有一个整数数组 nums 按升序排序(具有不同的值)。在传递给函数之前,nums 可能会在未知的主元索引 k (1 <= k < nums.length) 处进行旋转,从而生成的数组为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]

给定可能旋转后的数组 nums 和整数 target,如果 target 位于 nums 中,则返回 target 的索引,如果不在 nums 中,则返回 -1

您必须编写一个运行时间复杂度为 O(log n) 的算法。

编写一个函数 search(nums: List[int], target: int) -> int

约束条件
  • 1 <= len(nums) <= 5000
  • -10^4 <= nums[i] <= 10^4
  • All values of nums are unique
  • nums is an ascending array that is possibly rotated
  • -10^4 <= target <= 10^4

示例

Example 1
Input
nums = [4, 5, 6, 7, 0, 1, 2], target = 0
Output
4
Explanation

0 is found at index 4.

Example 2
Input
nums = [4, 5, 6, 7, 0, 1, 2], target = 3
Output
-1
Explanation

3 is not in the array.

Example 3
Input
nums = [1], target = 0
Output
-1
Explanation

0 is not in the array.

Need a Hint?
考虑使用二分搜索特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。