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,返回谁都一样
相关推荐
君为先-bey7 分钟前
LeMiCa——基于扩散模型的高效视频生成的词典序最小化路径缓存
python·算法·机器学习·扩散模型
L_cl21 分钟前
大模型应用开发 9.FastAPI ① 请求与响应
python·fastapi
洛水水28 分钟前
【力扣100题】58.轮转数组
算法·leetcode
风筝在晴天搁浅43 分钟前
阿里 LeetCode 876.链表的中间节点
算法·leetcode·链表
玖釉-1 小时前
二叉树展开为链表:从先序遍历到原地指针重排
c++·windows·算法·leetcode·链表
treesforest1 小时前
机房IP是什么?有什么危害?如何识别?
网络·数据库·python·网络协议·tcp/ip·网络安全
洛水水1 小时前
【力扣100题】52.最小路径和
算法·leetcode
圣保罗的大教堂2 小时前
leetcode 3043. 最长公共前缀的长度 中等
leetcode
咕白m6252 小时前
Excel 工作表名称读取(Python 实现)
后端·python
godspeed_lucip2 小时前
LLM和Agent——专题5: LLM Ops 入门(1)
人工智能·python