LeetCode | 搜索插入位置

248 字
1 分钟
LeetCode | 搜索插入位置

分类:二分查找 / 数组

题目#

给定一个升序数组 nums 和一个目标值 target

如果 target 在数组中,返回它的下标;如果不在数组中,返回它应该插入的位置。

示例:

输入:nums = [1,3,5,6], target = 5
输出:2
输入:nums = [1,3,5,6], target = 2
输出:1

讲解#

二分法,直接看代码。非常之清晰。 二分法的范围通过双指针实现。

复杂度#

  • 暴力做法:
    • 时间复杂度:O(n)
    • 空间复杂度:O(1)
  • 二分查找:
    • 时间复杂度:O(log(n))
    • 空间复杂度:O(1)

代码#

源码#

from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums)
while left < right:
mid = (left + right) // 2
if nums[mid] < target:
left = mid + 1
else:
right = mid
return left

测试#

from src.python._035_Search_Insert_Position import Solution
sol = Solution()
assert sol.searchInsert([1, 3, 5, 6], 5) == 2
assert sol.searchInsert([1, 3, 5, 6], 2) == 1
assert sol.searchInsert([1, 3, 5, 6], 7) == 4
assert sol.searchInsert([1, 3, 5, 6], 0) == 0
print("PASS")

参考资料#

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

LeetCode | 搜索插入位置
https://leetcode.cn/problems/search-insert-position/
作者
平昊阳
发布于
2026-08-04
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
平昊阳
乘长风,破巨浪, 展鸿图于未央!
--
总访问量
--
访客数
公告
欢迎来到我的个人博客!欢迎关注交流吖!
更多相关公告,见
社交-留言」。
音乐
封面

音乐

暂未播放

0:000:00
暂无歌词
站点统计
文章
66
分类
16
标签
93
总字数
477,284
运行时长
0
最后活动
0 天前

文章目录