LeetCode_Python3: 35. 搜索插入位置(简单)

开始之前:从2018/8/27开始刷LeetCode,计划每周刷五题,周末进行总结并发布在csdn上,计划先刷150道题,从简单开始。

week 3-1


要求:

 

CODE:

class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        # 如果要搜索的目标存在与数组中则直接输出
        if target in nums:
            return nums.index(target)
        
        # 设置index上下限
        left = 0
        right = len(nums) - 1
        while left <= right:
            mid = (left + right) // 2
            if target < nums[mid]:
                right = mid - 1
            elif target > nums[mid]:
                left = mid + 1
            else:
                return mid
        return left

 

          

结果:

 

备注:其实我一开始挺震惊的,这个竟然比我快,大概是48ms,只是一个简单的for循环,后来想想也有道理。二叉查找的复杂度是O(long2n),最耗时的情况就是target不存在于nums中,而这种情况看来在测试例中相当常见。

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

注意:该题使用二分查找

二分查找的代码应该牢记,这里贴出来供大家参考:

def binarySearch(target, nums):
    """
    二分查找的前提是原数组已排序
    """
    
    # 定义索引上限和下限
    left = 0
    right = len(nums) - 1
    
    while left <= right:
        mid = (left + right) // 2
        if target < nums[mid]:
            right = mid - 1
        elif target > nums[mid]:
            left = mid + 1
        else:
            return mid
    return left  # 当数组中不存在target时会返回其应该排序的位置

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值