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
返回索引
相关推荐
smj2302_796826524 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
_深海凉_8 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
踩坑记录8 小时前
leetcode hot100 寻找两个正序数组的中位数 hard 二分查找 双指针
leetcode
superior tigre11 小时前
78 子集
算法·leetcode·深度优先·回溯
superior tigre13 小时前
739 每日温度
算法·leetcode·职场和发展
6Hzlia13 小时前
【Hot 100 刷题计划】 LeetCode 15. 三数之和 | C++ 排序+双指针
c++·算法·leetcode
北顾笙98015 小时前
day37-数据结构力扣
数据结构·算法·leetcode
6Hzlia17 小时前
【Hot 100 刷题计划】 LeetCode 189. 轮转数组 | C++ 三次反转经典魔法 (O(1) 空间)
c++·算法·leetcode
m0_6294947318 小时前
LeetCode 热题 100-----13.最大子数组和
数据结构·算法·leetcode
田梓燊18 小时前
力扣:94.二叉树的中序遍历
数据结构·算法·leetcode