862. 和至少为 K 的最短子数组

给你一个整数数组 nums 和一个整数 k ,找出 nums 中和至少为 k 的 最短非空子数组 ,并返回该子数组的长度。如果不存在这样的 子数组 ,返回 -1 。

子数组 是数组中 连续 的一部分。

示例 1:

输入:nums = [1], k = 1
输出:1
输入:nums = [1,2], k = 4
输出:-1
输入:nums = [2,-1,2], k = 3
输出:3
class Solution(object):
    def shortestSubarray(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        # 原数组i-j之间的和至少为k,前缀和数组sum_j - sum_i的差至少为K
        preSumArr = [0]
        for num in nums:
            preSumArr.append(preSumArr[-1] + num)#构建前缀和数组
        q = deque() #队列(单调递增)
        res = len(nums)+1
        for i,curSum in enumerate(preSumArr):
    #通过下标位的差值更新最短子数组的长度,在更新的同时要将当前位置删除
            while q and curSum - preSumArr[q[0]] >= k:
                res = min(res,i-q.popleft())
    #当q中存在比preSumArr[i]更大的元素,应该弹出,否则更难满足不等式preSumArr[i]-preSumArr[j]>=k
            while q and curSum <= preSumArr[q[-1]]:
                q.pop()
            
            q.append(i)
        #判断当前数组是否是该数组的子数组,不是返回-1
        return res if res<len(nums)+1 else -1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值