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
返回索引
相关推荐
文丑颜不良啊15 小时前
LeetCode3281~3300题目解析
java·leetcode
文丑颜不良啊19 小时前
LeetCode3261~3280题目解析
java·leetcode
Rain的Java大神之路21 小时前
LeetCode 40 组合总和 II:面试官想听的不是回溯,而是那行去重代码
java·leetcode·面试
ashiho1 天前
【LeetCode hot 100】3. 无重复字符的最长子串 (三种解法)
java·数据结构·后端·算法·leetcode·滑动窗口
Pniubi2 天前
01背包类问题-力扣416.分割等和子集
算法·leetcode·职场和发展
文丑颜不良啊2 天前
LeetCode3041~3060题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode3101~3120题目解析
java·leetcode
玄昌盛不会编程3 天前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
文丑颜不良啊3 天前
LeetCode3061~3080题目解析
java·leetcode
文丑颜不良啊3 天前
LeetCode3081~3100题目解析
java·leetcode