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,返回谁都一样
相关推荐
用户83562907805113 分钟前
使用 Python 在 PDF 中绘制线条、矩形和自定义图形
后端·python
wang_yb28 分钟前
用方差阈值过滤掉“惰性特征”
python·ai·databook
RFID固定资产管理系统2 小时前
公司RFID管理系统揭秘
大数据·python
IVEN_2 小时前
Python官方包、Conda、uv,应该怎么选
python
玖玥拾2 小时前
LeetCode 27 移除元素
算法·leetcode
凡尘——雨落凡尘3 小时前
Python列表索引越界IndexError问题深度解析与解决办法
python·indexerror·list index out of range
Metaphor6923 小时前
使用 Python 在 Word 文档中添加或删除文本框
python·word
郝同学今天有进步吗4 小时前
构建 LangGraph Code Review Agent(七):实现规则匹配、Finding Guardrails 与 Markdown 报告
python·ai·fastapi·code review
xuhe24 小时前
一劳永逸!解决 AutoDL 系统盘(30GB)爆满与 pip 缓存迁移
linux·python·ai·jupyter
hanlin034 小时前
刷题笔记:力扣第704、977、209题(数组相关)
笔记·算法·leetcode