LeetCode 题解工作台

搜索插入位置

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 请必须使用时间复杂度为 O(log n) 的算法。 示例 1: 输入: nums = [1,3,5,6], target = 5 输出: 2 示例 2: 输入: nums = […

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 二分·搜索·答案·空间

bolt

答案摘要

由于 数组已经有序,因此我们可以使用二分查找的方法找到目标值 的插入位置。 时间复杂度 $O(\log n)$,空间复杂度 。其中 为数组 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

请必须使用时间复杂度为 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] <= 104
  • nums 为 无重复元素 的 升序 排列数组
  • -104 <= target <= 104
lightbulb

解题思路

方法一:二分查找

由于 numsnums 数组已经有序,因此我们可以使用二分查找的方法找到目标值 targettarget 的插入位置。

时间复杂度 O(logn)O(\log n),空间复杂度 O(1)O(1)。其中 nn 为数组 numsnums 的长度。

1
2
3
4
5
6
7
8
9
10
11
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

搜索插入位置题解:二分·搜索·答案·空间 | LeetCode #35 简单