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,返回谁都一样
相关推荐
小田学Python6 小时前
100行Python代码,搭一个能干活的AI Agent
python·langchain·大模型·ai agent
Csvn6 小时前
🐍 Day3 : Python 容器精讲 — list、dict、set、tuple 底层实现与高级操作
后端·python
weixin-a153003083167 小时前
python-装饰器
开发语言·python
我的xiaodoujiao7 小时前
快速学习Python基础知识详细图文教程17--类型注解和断点调试
开发语言·python·学习·测试工具
.道阻且长.7 小时前
5.LeetCode算法习题讲解--双指针--有效三角形的个数
算法·leetcode·职场和发展
每天吃饭的羊8 小时前
Chrome DevTools MCP
python
水獭比特10 小时前
localhost 不是安全边界:给 Agent Web 入口补上四层门禁
人工智能·python
Generalzy10 小时前
Whisper + VAD + TTS:一套完整的 Python 本地语音处理流水线
python·whisper·语音识别
qpsj10 小时前
让 LLM 控制 AutoCAD/ZWCAD:COM 自动化 + MCP 封装
python·llm
赟爸10 小时前
直播切片素材杂乱不好复用,易元AI要怎么处理
大数据·人工智能·python