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,返回谁都一样
相关推荐
爱吃苹果的梨叔15 小时前
2026年指挥中心分布式坐席怎么选?清虹创智让多系统、多坐席和大屏真正协同
python
起予者汝也16 小时前
Python 数据结构
开发语言·数据结构·python
LadenKiller16 小时前
2026年量化工具增量,放回回测模拟实盘阶段判断
人工智能·python
石一峰69916 小时前
驱动:私有数据为什么要在三个地方各挂一遍?
数据库·python·算法
2601_9563198816 小时前
最新量化软件怎么选,先按能力短板匹配工具类型
人工智能·python
Tbisnic16 小时前
26.AI大模型:RNN、LSTM、GRU
人工智能·python·rnn·gru·大模型·llm·lstm
七夜zippoe17 小时前
OpenClaw 实战:智能文档助手——从问答到生成的完整方案
人工智能·python·机器学习·openclaw·智能文档
卡提西亚17 小时前
leetcode-179. 最大数
python·算法
AC赳赳老秦18 小时前
时间开销自动统计:OpenClaw 记录工作任务时长、分析时间分配、给出优化建议
java·大数据·开发语言·python·自动化·deepseek·openclaw
Frostnova丶18 小时前
(17)LeetCode 41. 缺失的第一个正数
数据结构·算法·leetcode