LeetCode 862 Shortest Subarray with Sum at Least K (单调队列 推荐)

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

Note:

  1. 1 <= A.length <= 50000
  2. -10 ^ 5 <= A[i] <= 10 ^ 5
  3. 1 <= K <= 10 ^ 9

题目链接:https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/

题目分析:本题的思维过程:

首先用公式把题目抽象出来,设sum[i]为A数组的前缀和,则题目变为

求min(j - i) ,限制条件为 j > i && sum[j]-sum[i]>=K

设下标i和j满足j>i且sum[j]j,若sum[k]-sum[i]>=K,则必然有sum[k]-sum[j]>=K,且k > j > i,即之后若存在和i位置相减满足大于等于K的位置,其和j位置相减必然满足大于等于K且其与j的距离更近,在这种情况下sum[i]可被丢弃,分析到这已经很容易想到用一个单调的数据结构维护了,这里采用单调队列来维护前缀和,队首到队尾递增,继续分析,假设当前位置为i,因为首先要满足子区间和大于等于K,故从队首开始遍历,队列中满足条件的点均可出队,因为i之后的元素即使满足条件也不可能比i里它们更近。

最终其实就是一个滑动窗口,速度击败98.5%,手动deque

class Solution {
    public int shortestSubarray(int[] A, int K) {
        int[] sum = new int[A.length + 5];
        int[] deque = new int[A.length + 5];
        Arrays.fill(sum, 0);
        Arrays.fill(deque, 0);
        for (int i = 0; i < A.length; i++) {
            sum[i + 1] = sum[i] + A[i];
        }
        int st = 0, ed = 0, ans = A.length + 1;
        for (int i = 0; i <= A.length; i++) {
            while (st < ed && sum[i] - sum[deque[st]] >= K) {
                ans = Math.min(ans, i - deque[st++]);
            }
            while (st < ed && sum[i] <= sum[deque[ed - 1]]) {
                ed--;
            }
            deque[ed++] = i;
        }
        return ans == A.length + 1 ? -1 : ans;
    }
}

 

你可能感兴趣的:(数据结构,Leetcode,Hard,LeetCode)