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
返回索引
相关推荐
凌波粒13 小时前
LeetCode--404.左叶子之和(二叉树)
算法·leetcode·职场和发展
绝知此事14 小时前
【算法突围 03】核心算法思想:分治/递归/动态规划与 LeetCode 高频真题解析
算法·leetcode·面试·动态规划
阿Y加油吧15 小时前
两道字符串 DP 模板题复盘:最长公共子序列 & 编辑距离
leetcode
我爱cope15 小时前
【力扣hot100:76. 最小覆盖子串】
算法·leetcode·职场和发展
sheeta199816 小时前
LeetCode 每日一题笔记 日期:2026.05.20 题目:2657. 找到前缀公共数组
笔记·算法·leetcode
吃着火锅x唱着歌17 小时前
LeetCode 962.最大宽度坡
算法·leetcode·职场和发展
凌波粒17 小时前
LeetCode--257. 二叉树的所有路径(二叉树)
算法·leetcode·职场和发展
阿Y加油吧18 小时前
两道数组算法题复盘:多数元素 & 颜色分类
算法·leetcode·职场和发展
And_Ii19 小时前
LeetCode 026. 重排链表
算法·leetcode·链表
是娇娇公主~19 小时前
力扣——146.LRU缓存详解
算法·leetcode·缓存