LeetCode 题解工作台
二分查找
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target ,如果 target 存在返回下标,否则返回 -1 。 你必须编写一个具有 O(log n) 时间复杂度的算法。 示例 1: 输入: nums = [-1,0,3,5,9…
2
题型
8
代码语言
3
相关题
当前训练重点
简单 · 二分·搜索·答案·空间
答案摘要
我们定义二分查找的左边界 ,右边界 。 每一次循环,我们计算中间位置 ,然后比较 和 的大小。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果 target 存在返回下标,否则返回 -1。
你必须编写一个具有 O(log n) 时间复杂度的算法。
示例 1:
输入:nums= [-1,0,3,5,9,12],target= 9 输出: 4 解释: 9 出现在nums中并且下标为 4
示例 2:
输入:nums= [-1,0,3,5,9,12],target= 2 输出: -1 解释: 2 不存在nums中因此返回 -1
提示:
- 你可以假设
nums中的所有元素是不重复的。 n将在[1, 10000]之间。nums的每个元素都将在[-9999, 9999]之间。
解题思路
方法一:二分查找
我们定义二分查找的左边界 ,右边界 。
每一次循环,我们计算中间位置 ,然后比较 和 的大小。
- 如果 ,说明 在左半部分,我们将右边界 移动到 ;
- 否则,说明 在右半部分,我们将左边界 移动到 。
循环结束的条件是 ,此时 就是我们要找的目标值,如果 ,返回 ,否则返回 。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def search(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums) - 1
while l < r:
mid = (l + r) >> 1
if nums[mid] >= target:
r = mid
else:
l = mid + 1
return l if nums[l] == target else -1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(\log n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Can the candidate efficiently explain how binary search works and its time complexity?
- question_mark
Does the candidate implement the binary search algorithm correctly without unnecessary computations?
- question_mark
Does the candidate handle edge cases, such as when the target is not present, effectively?
常见陷阱
外企场景- error
Misunderstanding the search space boundaries; incorrect pointer updates may lead to infinite loops or missing the correct index.
- error
Not properly handling the case when the target is not found, leading to incorrect return values.
- error
Overcomplicating the solution by adding unnecessary checks or conditions that don't affect the binary search logic.
进阶变体
外企场景- arrow_right_alt
Search for the target value in a descending sorted array.
- arrow_right_alt
Find the first occurrence of the target if there are duplicates.
- arrow_right_alt
Implement a binary search that finds the closest value to the target when it’s not present.