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
返回索引
相关推荐
-海绵东东-4 小时前
哈希表······················
算法·leetcode·散列表
菜鸡儿齐5 小时前
leetcode-全排列
算法·leetcode·深度优先
不想看见4045 小时前
Maximal Square 基本动态规划:二维--力扣101算法题解笔记
算法·leetcode·动态规划
夏乌_Wx5 小时前
LeetCode 160. 相交链表 | 三种解法吃透核心逻辑(哈希表 + 双指针 + 长度对齐)
leetcode·链表·哈希表
Hag_205 小时前
LeetCode Hot100 53.最大子数组和
数据结构·算法·leetcode
pursuit_csdn5 小时前
LeetCode 1461. Check If a String Contains All Binary Codes of Size K
算法·leetcode·职场和发展
Crazy________6 小时前
力扣113个mysql简单题解析(包含plus题目)
mysql·算法·leetcode·职场和发展
初次攀爬者7 小时前
力扣解题-无重复字符的最长子串
后端·算法·leetcode
圣保罗的大教堂7 小时前
leetcode 1461. 检查一个字符串是否包含所有长度为 K 的二进制子串 中等
leetcode