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,返回谁都一样
相关推荐
mengge.cloud22 分钟前
Python基础保姆级!从入门到入土
开发语言·python·云原生·pygame
qq_158895411115 小时前
Suno-API 是什么?官方 V6 模型与 Python / TypeScript 接入指南
python·ai音乐·suno api
学无止境小袁同学15 小时前
Google ADK 学习指南
python·llm·agent·多agent·google adk·llmagent·agent cli
郝学胜-神的一滴15 小时前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
LK_0716 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
wuyk55516 小时前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
Pniubi16 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
用户548178459095017 小时前
Java 与 Python 在大模型与智能体领域的选型
java·python
文丑颜不良啊17 小时前
LeetCode3341~3360题目解析
java·leetcode