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,返回谁都一样
相关推荐
理想是做全栈工程师13 小时前
基于UNet的带噪黑白数字图像分割模型
人工智能·pytorch·python·anaconda
lbb 小魔仙13 小时前
从零搭建 Spring Cloud 微服务项目:注册中心 + 网关 + 配置中心全流程
java·python·spring cloud·微服务
霖雨14 小时前
备份 SQL Server 到 Azure Storage
后端·python·microsoft·flask·azure
tjjucheng14 小时前
小程序定制开发哪家有团队支持
python
我送炭你添花14 小时前
Pelco KBD300A 模拟器:08.模板库 + 一键场景加载
运维·开发语言·python·自动化
weixin_4624462314 小时前
JupyterLab 禁用 Terminal 的三种方法(安装记录,仅供参考)
python·jupyter·jupyterlab
飞Link14 小时前
数据增强中的数据标注、数据重构、协同标注和非LLM驱动的增强
python·重构·数据挖掘
惜.己14 小时前
使用python复制目录以及目录的子目录的文件到脚本运行的目录(工具+源码)
python
副露のmagic14 小时前
更弱智的算法学习day 38
python·学习