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,返回谁都一样
相关推荐
Samooyou5 分钟前
大模型微调(Fine Tuning)
人工智能·python·ai·语言模型
qq_8573058197 分钟前
python语法
开发语言·python·算法
AI行业学习21 分钟前
CC-Switch v3.16.1 官方下载 | 安装配置详细教程【2026.6.10】
java·开发语言·vue.js·python·mysql·eclipse·html
早起CaiCai1 小时前
【Pytorch 实践1】手写数字
人工智能·pytorch·python
吴梓穆1 小时前
Python 语法基础 函数
开发语言·python
Kobebryant-Manba1 小时前
学习文本处理
开发语言·python
m0_617493941 小时前
PaddleOCR报错:OneDnnContext does not have the input Filter 解决方案汇总
python
李可以量化1 小时前
量化迅投 QMT vs 聚宽 (JoinQuant)全面分析
python·量化·qmt·ptrade·聚宽
旅僧1 小时前
运行UMI镜像
python
ellenwan20261 小时前
期货跨期价差程序化怎么做:天勤 SP 合约与腿比例核对
python·区块链