leetcode35:搜索插入位置

本文介绍了两种查找插入位置的算法思想:一种是遍历查找,适用于小规模数据,但效率较低;另一种是折半查询法,由大佬提出,适用于大规模数据,通过不断缩小搜索范围提高查找效率。文章对比了两种方法,并详细解析了折半查询法的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思想:

1.判断target是否大于等于nums[i],若是则return i,反之继续1

2.若循环结束,则返回len(nums)

class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        for i in range(0, len(nums)):
            if target <= nums[i]:
                return i
        return len(nums)


if __name__ == "__main__":
    print(Solution().searchInsert([1,3,5,6], 7))

小菜鸟的思想,哈哈哈哈哈。(这样有点耗时呢,可以采取折半查询法)

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        left, right = 0, len(nums) - 1
        while left <= right:
            mid = left + (right - left) / 2
            if nums[mid] >= target:
                right = mid - 1
            else:
                left = mid + 1

        return left

以上是大佬的思想,学习学习

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值