LeetCode 862 题解

https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/description/

题目大意:求满足数组内,连续和至少为K的一个序列,使得这个序列最短,求最短的长度。

解题思路:P[x]表示数列的前缀和,考虑点 x1 ,x2 若 x1<x2 ,且P[x1]>=p[x2],那么选择x2肯定来的比x1短;

考虑y1<y2,若 满足 y1 ,y2都是x点,那么y1肯定比y2好。

维护一个双端队列,每次入队前 和 尾端的P[x]比较,若比原来的小则弹出原来的值;

和队首比较,若满足差值至少为K,则将队首的值出列。

 

class Solution {
    public int shortestSubarray(int[] A, int K) {
        int n = A.length;
        long[] p = new long[n+1];
        for(int i=0;i<n;i++)
            p[i+1] = (A[i] + p[i]);
        Deque<Integer> qt = new LinkedList<>();
        int res = n +1;
        for(int i=0;i<=n;i++)
        {
            System.out.println(p[i]);
            while(!qt.isEmpty() && p[i]<=p[qt.getLast()]) {
//                System.out.println("!"+" "+p[qt.getLast()]);
                qt.removeLast();
            }
            while(!qt.isEmpty() && p[i]>=p[qt.getFirst()]+K) {
//                System.out.println("!"+" "+p[qt.getFirst()]);
                res = Math.min(res, i - qt.removeFirst());
//                System.out.println(qt.getFirst()+" "+p[qt.getFirst()]);
            }
            qt.addLast(i);
        }
        return (res==n+1)?-1:res;
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值