150强访谈简单

二分查找

“二分查找”问题的详细指南和 Python 实现。

问题陈述

简单

给定一个按升序排序的整数数组 nums 和一个整数 target,编写一个函数在 nums 中搜索 target。如果 target 存在,则返回其索引。否则,返回 -1

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

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

约束条件
  • 1 <= len(nums) <= 10^4
  • -10^4 < nums[i], target < 10^4
  • All integers in nums are unique
  • nums is sorted in ascending order

示例

Example 1
Input
nums = [-1, 0, 3, 5, 9, 12], target = 9
Output
4
Explanation

9 exists in nums and its index is 4.

Example 2
Input
nums = [-1, 0, 3, 5, 9, 12], target = 2
Output
-1
Explanation

2 does not exist in nums so return -1.

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 资源

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