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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-subarray-with-sum-at-least-k
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.LinkedList;
import java.util.Map;

class Solution {
    public int shortestSubarray(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return -1;
        }

        long[] sum = new long[nums.length + 1];
        for (int i = 1; i <= nums.length; ++i) {
            sum[i] = sum[i - 1] + nums[i - 1];
        }

        int ret = Integer.MAX_VALUE;
        LinkedList<Integer> queue = new LinkedList<>();
        queue.offerLast(0);
        for (int i = 1; i <= nums.length; ++i) {
            while (!queue.isEmpty() && sum[i] - sum[queue.peekFirst()] >= k) {
                ret = Math.min(ret, i - queue.pollFirst());
            }

            while (!queue.isEmpty() && sum[queue.peekLast()] >= sum[i]) {
                queue.pollLast();
            }

            queue.offerLast(i);

        }

        return ret == Integer.MAX_VALUE ? -1 : ret;
    }
}
posted @ 2021-12-15 21:47  Tianyiya  阅读(51)  评论(0)    收藏  举报