LeetCode 题解工作台
搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 请必须使用时间复杂度为 O(log n) 的算法。 示例 1: 输入: nums = [1,3,5,6], target = 5 输出: 2 示例 2: 输入: nums = […
2
题型
8
代码语言
3
相关题
当前训练重点
简单 · 二分·搜索·答案·空间
答案摘要
由于 数组已经有序,因此我们可以使用二分查找的方法找到目标值 的插入位置。 时间复杂度 $O(\log n)$,空间复杂度 。其中 为数组 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
示例 1:
输入: nums = [1,3,5,6], target = 5 输出: 2
示例 2:
输入: nums = [1,3,5,6], target = 2 输出: 1
示例 3:
输入: nums = [1,3,5,6], target = 7 输出: 4
提示:
1 <= nums.length <= 104-104 <= nums[i] <= 104nums为 无重复元素 的 升序 排列数组-104 <= target <= 104
解题思路
方法一:二分查找
由于 数组已经有序,因此我们可以使用二分查找的方法找到目标值 的插入位置。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums)
while l < r:
mid = (l + r) >> 1
if nums[mid] >= target:
r = mid
else:
l = mid + 1
return l
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ability to apply binary search to solve problems efficiently.
- question_mark
Experience in handling edge cases like insertion boundaries and array size limits.
- question_mark
Understanding of O(log n) time complexity and its application in real-world algorithms.
常见陷阱
外企场景- error
Forgetting to update the boundaries correctly in binary search, leading to incorrect results.
- error
Not considering edge cases, like inserting at the start or end of the array.
- error
Incorrectly handling arrays with only one element or very large arrays.
进阶变体
外企场景- arrow_right_alt
Modifying the problem to handle arrays with duplicate values.
- arrow_right_alt
Allowing multiple target values and returning all possible insert positions.
- arrow_right_alt
Introducing a constraint where the array is not sorted, requiring sorting before binary search.