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】从递归到 Flood Fill:5 道题吃透 DFS 的选择、回溯与标记
java·算法·leetcode·深度优先·回溯·flood fill
evans在进步13 小时前
LeetCode 33:搜索旋转排序数组——Java 两阶段二分查找详解
java·python·leetcode
Forever Nore15 小时前
LeetCode 13 罗马数字转整数 - 按规则处理
linux·服务器·leetcode
旖旎夜光16 小时前
LeetCode 904:水果成篮(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
ZC跨境爬虫17 小时前
LeetCode 27. 移除元素(双指针详解 + Java Python 多解法对比)
java·python·leetcode
LuminousCPP19 小时前
单链表专题(四)-刷题复盘篇-LeetCode 138 随机链表复制|原地拷贝法突破复杂指针操作
数据结构·笔记·算法·leetcode·链表
Forever Nore20 小时前
LeetCode 14 最长公共前缀 - 纵向扫描
linux·服务器·leetcode
圣保罗的大教堂20 小时前
leetcode 3090. 每个字符最多出现两次的最长子字符串 简单
leetcode
旖旎夜光1 天前
LeetCode 3:无重复字符的最长子串(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
Navigator_Z1 天前
LeetCode //C - 1192. Critical Connections in a Network
c语言·算法·leetcode