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,返回谁都一样
相关推荐
文言一心1 小时前
LINUX离线升级 Python 至 3.11.9 操作手册
linux·运维·python
诗词在线1 小时前
中国古代诗词名句按主题分类有哪些?(爱国 / 思乡 / 送别)
人工智能·python·分类·数据挖掘
高锰酸钾_1 小时前
机器学习-L1正则化和L2正则化解决过拟合问题
人工智能·python·机器学习
AlenTech1 小时前
155. 最小栈 - 力扣(LeetCode)
算法·leetcode·职场和发展
天天睡大觉2 小时前
Python学习11
网络·python·学习
智航GIS2 小时前
11.11 Pandas性能革命:向量化操作与内存优化实战指南
python·pandas
写代码的【黑咖啡】3 小时前
Python中的Selenium:强大的浏览器自动化工具
python·selenium·自动化
抠头专注python环境配置3 小时前
解决Windows安装PythonOCC报错:从“No module named ‘OCC’ ”到一键成功
人工智能·windows·python·3d·cad·pythonocc
坚持不懈的大白3 小时前
Leetcode学习笔记
笔记·学习·leetcode