从零开始刷LeetCode:[35] 搜索插入位置

题目描述:https://leetcode-cn.com/problems/search-insert-position/description/

思路:

  1. 假设所给数组是[a1,a2,...,an],在左右两边加入无穷大和负无穷大,[-inf,a1,a2,...,an,inf]
  2. 在数组中寻找ai < target <=ai+1,返回 i

按照这种思路,编写代码:

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:

        length = len(nums)
        nums = [-float('inf')] + nums + [float('inf')]

        for i in range(0,length+1):
            if nums[i] < target <= nums[i+1] or i == length:
                break
        
        return i

这样写,有些复杂,参考别人的代码,可以简化为:

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        i = 0
        while i<len(nums) and nums[i]<target:
            i = i + 1
        return i

还可以通过二分法,降低运算速度:

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        low = 0
        high = len(nums)
        while low < high:
            mid = low + (high - low)/2
            if nums[mid] > target:
                high = mid
            elif nums[mid] < target:
                low = mid +1
            else:
                return mid
        return low
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值