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,返回谁都一样
相关推荐
Navigator_Z17 分钟前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
fengkai454535 分钟前
Python运维实战
运维·开发语言·python·ssh·sftp·paramiko
用户45428451062811 小时前
一张 3000×2000 的 PSD 为什么 86MB:从体积构成到上传墙
python
用户298698530142 小时前
使用 Python 提取 Word 文档中的文本与图片
后端·python·api
用户0332126663672 小时前
使用 Python 在 PDF 中创建表单域
python
羲云网络12 小时前
GPT Image 2.6 海报改横竖版:文字安全区、排版分离与交付验收
图像处理·人工智能·python·aigc
曲径海盗13 小时前
【Python 学习第 65 天】字典基础
python·学习笔记·编程入门
Wellijohn14 小时前
Docker 瘦身、手写 MCP、异步并发:被问得最多的 12 个问题,一次答完
python·docker·mcp
VW_40417 小时前
csdn-2026-11-23-第一站踩坑
爬虫·python
Navigator_Z17 小时前
LeetCode //C - 1318. Minimum Flips to Make a OR b Equal to c
c语言·算法·leetcode