Python | Leetcode Python题解之第35题搜索插入位置

题目:

题解:

python 复制代码
class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        left, right = 0, len(nums) #采用左闭右开区间[left,right)
        while left < right: # 右开所以不能有=,区间不存在
            mid = left + (right - left)//2 # 防止溢出, //表示整除
            if nums[mid] < target: # 中点小于目标值,在右侧,可以得到相等位置
                left = mid + 1 # 左闭,所以要+1
            else:
                right = mid # 右开,真正右端点为mid-1
        return left # 此算法结束时保证left = right,返回谁都一样
相关推荐
copyer_xyf3 小时前
Python 类型注解:从 TypeScript 迁移理解
前端·后端·python
8Qi83 小时前
LeetCode 474:一和零(Ones and Zeroes)—— 题解 ✅
算法·leetcode·职场和发展·动态规划·01背包
27669582923 小时前
谷歌google cookie逆向角度分析
开发语言·python·google·sgss·谷歌搜索·sg-ss·谷歌cookie逆向
copyer_xyf3 小时前
Python 函数全面总结
前端·后端·python
zmzb01033 小时前
Python课后习题训练记录Day123
开发语言·python
PersistJiao3 小时前
python环境下免费、专业的中英翻译
开发语言·windows·python·机器翻译
hujinyuan201603 小时前
中国电子学会青少年软件编程(Python)(二级)等级考试试卷-真题+答案(2026年3月)
python·机器人
Lsk_Smion3 小时前
力扣实训 _ [98].验证二叉搜索树 _ 将二叉树展开成链表
数据结构·算法·leetcode
老毛肚3 小时前
记一次逆向
开发语言·python