leetcode hot100 35. 搜索插入位置 medium 二分查找


coffeescript 复制代码
class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        left = 0
        right = len(nums)-1

        while left <= right:

            mid = (left+right)//2  # 中间索引

            if nums[mid] > target:
                right = mid -1   # mid 已经比较过,不能再参与下一轮
            elif nums[mid] < target:
                left = mid +1
            else:
                return mid   # nums[mid] == target 返回坐标
                
        # 循环结束时 left > right 
        # 此时:right 指向最后一个 < target 的位置
        # left 指向第一个 ≥ target 的位置
        # 如果找不到 target,返回它应该插入的位置(left)
        return left
      

            

为什么不能是:while left < right:,只能是while left <= right:

coffeescript 复制代码
right = mid - 1
left = mid + 1

这种更新方式是给:

coffeescript 复制代码
while left <= right

例子

coffeescript 复制代码
nums = [1,3]
target = 3

初始:

coffeescript 复制代码
left = 0
right = 1
mid = 0
nums[0] = 1 < 3
left = mid + 1 = 1

现在:

coffeescript 复制代码
left = 1
right = 1

如果循环条件是:

coffeescript 复制代码
while left < right
1 < 1  → False
循环直接结束!

如果循环条件是:

coffeescript 复制代码
while left <= right
1 <= 1  → ture
循环继续!
left = 1
right = 1
mid = 1
nums[0] = 1 = 3
返回索引
相关推荐
小肝一下1 小时前
3. 单链表
c语言·数据结构·c++·算法·leetcode·链表·dijkstra
tachibana21 小时前
hot100 前 K 个高频元素(347)
java·数据结构·算法·leetcode
To_OC9 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
旖-旎10 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
To_OC11 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
tachibana21 天前
hot100 数组中的第K个最大元素(215)
java·数据结构·算法·leetcode
晚笙coding1 天前
LeetCode 98:验证二叉搜索树 —— 从局部判断到全局范围约束的递归思想
算法·leetcode·职场和发展
兰令水1 天前
hot100【acm版】【2026.7.21打卡-java版本】
java·开发语言·算法·leetcode·面试
退休倒计时1 天前
【每日一题】LeetCode 131. 分割回文串 TypeScript
算法·leetcode·typescript
旖-旎2 天前
LeetCode 279:完全平方数(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题