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,返回谁都一样
相关推荐
我的xiaodoujiao8 分钟前
使用PyMySQL模块技术操作MySQL数据库
数据库·python·测试工具·mysql
卷无止境27 分钟前
终端里的AI辅助,一场正在发生的编程效率变革
后端·python
苏灿烤鱼27 分钟前
上下文写成文件系统,为什么向量还能静默丢?
python·github·agent
SamChan901 小时前
对比 4 种主流 PDF 文档解析方案:PyMuPDF vs pdfplumber vs Apache PDFBox vs 大模型 OCR
python·ai·pdf·ocr·apache·机器翻译
安_9 小时前
如何构建和使用向量索引?HNSW 和 IVF 有什么区别?
python·ai
counting money10 小时前
Java IO流详解:从InputStream到文件操作实战
java·开发语言·python
坚持学习前端日记11 小时前
Python SQLAlchemy ORM 从0到1精通实战手册(基础到复杂高阶)
数据库·python·oracle
北斗落凡尘11 小时前
LangGraph 入门实战(11)--输出模式
后端·python·langchain
雪碧聊技术12 小时前
安装Python(保姆级教程)
python·版本更新·python下载
++==12 小时前
JSON和Python的 四种核心容器
python·json