第二天:有序数组的平方和长度最小的子数组

题目
在这里插入图片描述
解答

class Solution(object):
    def sortedSquares(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        
        n = len(nums)
        result = [0]*n
        Left, Right, idx = 0, n-1, n-1

        while Left <= Right:#这里应该用小于等于而不是只是小于
            Left_Square = nums[Left]**2
            Right_Square = nums[Right]**2
            
            if Left_Square > Right_Square:
                Left+=1
                result[idx] = Left_Square
            else : #这里不能使用条件(右平方大于左平方)
                Right-=1
                result[idx] = Right_Square
            idx -=1 #将原序列两边元素较大的放在结果序列的末端以达到非递减的效果

        return result #记得返回值不要放进while循环里面

题目
在这里插入图片描述
解答

        minLen=float('inf')# 初始值设为无穷
        Left, Right = 0, len(nums)
        sum = 0
        for Right in range(len(nums)):
            sum += nums[Right]

            while sum >=target:
                minLen = min(minLen,Right - Left + 1)
                sum-= nums[Left]
                Left+=1

        return minLen if minLen !=float('inf') else 0 # 结果记得如果没有minLen的话输出0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值