【Lintcode】1507. Shortest Subarray with Sum at Least K

题目地址:

https://www.lintcode.com/problem/shortest-subarray-with-sum-at-least-k/description

给定一个数组 A A A,返回其最短的和大于等于给定数 K K K的子数组的长度。

思路是前缀和 + 单调队列。参考https://blog.csdn.net/qq_46105170/article/details/109590586。代码如下:

import java.util.ArrayDeque;
import java.util.Deque;

public class Solution {
    /**
     * @param A: the array
     * @param K: sum
     * @return: the length
     */
    public int shortestSubarray(int[] A, int K) {
        // Write your code here.
        if (A == null || A.length == 0) {
            return -1;
        }
        
        int[] preSum = new int[A.length + 1];
        for (int i = 0; i < A.length; i++) {
            preSum[i + 1] = preSum[i] + A[i];
        }
    
        Deque<Integer> deque = new ArrayDeque<>();

        int res = A.length + 1;
        for (int i = 0; i < preSum.length; i++) {
        	// 满足条件,则更新答案,并将队头出队
            while (!deque.isEmpty() && preSum[i] - preSum[deque.peek()] >= K) {
                res = Math.min(res, i - deque.peek());
                deque.poll();
            }
            
            // 违反严格单调上升性,则poll队尾
            while (!deque.isEmpty() && preSum[deque.peekLast()] >= preSum[i]) {
                deque.pollLast();
            }
            
            deque.offer(i);
        }
        
        return res <= A.length ? res : -1;
    }
}

时空复杂度 O ( l A ) O(l_A) O(lA)

你可能感兴趣的:(LC,栈,队列,串及其他数据结构,java,算法,leetcode)