Leetcode 862 Shortest Subarray with Sum at Least K (双指针)

Leetcode 862

问题描述

Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K.

If there is no non-empty subarray with sum at least K, return -1.

例子

Example 1:
Input: A = [1], K = 1
Output: 1

Example 2:
Input: A = [1,2], K = 4
Output: -1

Example 3:
Input: A = [2,-1,2], K = 3
Output: 3

方法

** Solution Java **
** 23ms, 54.11% **
** 53.6MB, 14.29% **
class Solution {
    public int shortestSubarray(int[] A, int K) {
        int n = A.length, res = n + 1;
        int[] B = new int[n + 1];
        for (int i = 0; i < n; ++i)
            B[i + 1] = B[i] + A[i];
        Deque<Integer> d = new ArrayDeque<>();
        for (int i = 0; i < n + 1; ++i) {
            while (0 < d.size() && K <= (B[i] - B[d.getFirst()]))
                res = Math.min(res, i - d.pollFirst());
            while (0 < d.size() && B[i] <= B[d.getLast()])
                d.pollLast();
            d.addLast(i);
        }
        return res <= n ? res : -1;
    }
}
posted @ 2020-03-18 13:55  willwuss  阅读(79)  评论(0编辑  收藏  举报