返回介绍

solution / 0800-0899 / 0862.Shortest Subarray with Sum at Least K / README_EN

发布于 2024-06-17 01:03:33 字数 3804 浏览 0 评论 0 收藏 0

862. Shortest Subarray with Sum at Least K

中文文档

Description

Given an integer array nums and an integer k, return _the length of the shortest non-empty subarray of _nums_ with a sum of at least _k. If there is no such subarray, return -1.

A subarray is a contiguous part of an array.

 

Example 1:

Input: nums = [1], k = 1
Output: 1

Example 2:

Input: nums = [1,2], k = 4
Output: -1

Example 3:

Input: nums = [2,-1,2], k = 3
Output: 3

 

Constraints:

  • 1 <= nums.length <= 105
  • -105 <= nums[i] <= 105
  • 1 <= k <= 109

Solutions

Solution 1

class Solution:
  def shortestSubarray(self, nums: List[int], k: int) -> int:
    s = list(accumulate(nums, initial=0))
    q = deque()
    ans = inf
    for i, v in enumerate(s):
      while q and v - s[q[0]] >= k:
        ans = min(ans, i - q.popleft())
      while q and s[q[-1]] >= v:
        q.pop()
      q.append(i)
    return -1 if ans == inf else ans
class Solution {
  public int shortestSubarray(int[] nums, int k) {
    int n = nums.length;
    long[] s = new long[n + 1];
    for (int i = 0; i < n; ++i) {
      s[i + 1] = s[i] + nums[i];
    }
    Deque<Integer> q = new ArrayDeque<>();
    int ans = n + 1;
    for (int i = 0; i <= n; ++i) {
      while (!q.isEmpty() && s[i] - s[q.peek()] >= k) {
        ans = Math.min(ans, i - q.poll());
      }
      while (!q.isEmpty() && s[q.peekLast()] >= s[i]) {
        q.pollLast();
      }
      q.offer(i);
    }
    return ans > n ? -1 : ans;
  }
}
class Solution {
public:
  int shortestSubarray(vector<int>& nums, int k) {
    int n = nums.size();
    vector<long> s(n + 1);
    for (int i = 0; i < n; ++i) s[i + 1] = s[i] + nums[i];
    deque<int> q;
    int ans = n + 1;
    for (int i = 0; i <= n; ++i) {
      while (!q.empty() && s[i] - s[q.front()] >= k) {
        ans = min(ans, i - q.front());
        q.pop_front();
      }
      while (!q.empty() && s[q.back()] >= s[i]) q.pop_back();
      q.push_back(i);
    }
    return ans > n ? -1 : ans;
  }
};
func shortestSubarray(nums []int, k int) int {
  n := len(nums)
  s := make([]int, n+1)
  for i, x := range nums {
    s[i+1] = s[i] + x
  }
  q := []int{}
  ans := n + 1
  for i, v := range s {
    for len(q) > 0 && v-s[q[0]] >= k {
      ans = min(ans, i-q[0])
      q = q[1:]
    }
    for len(q) > 0 && s[q[len(q)-1]] >= v {
      q = q[:len(q)-1]
    }
    q = append(q, i)
  }
  if ans > n {
    return -1
  }
  return ans
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文