跳转至

剑指 Offer II 008. 和大于等于 target 的最短子数组

题目描述

给定一个含有 n 个正整数的数组和一个正整数 target

找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度如果不存在符合条件的子数组,返回 0

 

示例 1:

输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。

示例 2:

输入:target = 4, nums = [1,4,4]
输出:1

示例 3:

输入:target = 11, nums = [1,1,1,1,1,1,1,1]
输出:0

 

提示:

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

 

进阶:

  • 如果你已经实现 O(n) 时间复杂度的解法, 请尝试设计一个 O(n log(n)) 时间复杂度的解法。

 

注意:本题与主站 209 题相同:https://leetcode.cn/problems/minimum-size-subarray-sum/

解法

方法一:双指针

我们使用双指针维护一个和小于 $target$ 的连续子数组。每次右边界 $j$ 向右移动一位,如果和大于等于 $target$,则更新答案的最小值,同时左边界 $i$ 向右移动,直到和小于 $target$。

最后,如果答案没有被更新过,返回 $0$,否则返回答案。

时间复杂度 $O(n)$,其中 $n$ 是数组的长度。空间复杂度 $O(1)$。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        ans = inf
        s = i = 0
        for j, x in enumerate(nums):
            s += x
            while s >= target:
                ans = min(ans, j - i + 1)
                s -= nums[i]
                i += 1
        return 0 if ans == inf else ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        final int inf = 1 << 30;
        int ans = inf;
        int s = 0;
        for (int i = 0, j = 0; j < nums.length; ++j) {
            s += nums[j];
            while (s >= target) {
                ans = Math.min(ans, j - i + 1);
                s -= nums[i++];
            }
        }
        return ans == inf ? 0 : ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        const int inf = 1 << 30;
        int ans = inf;
        int n = nums.size();
        int s = 0;
        for (int i = 0, j = 0; j < n; ++j) {
            s += nums[j];
            while (s >= target) {
                ans = min(ans, j - i + 1);
                s -= nums[i++];
            }
        }
        return ans == inf ? 0 : ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
func minSubArrayLen(target int, nums []int) int {
    const inf = 1 << 30
    ans := inf
    s, i := 0, 0
    for j, x := range nums {
        s += x
        for s >= target {
            ans = min(ans, j-i+1)
            s -= nums[i]
            i++
        }
    }
    if ans == inf {
        return 0
    }
    return ans
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function minSubArrayLen(target: number, nums: number[]): number {
    const n = nums.length;
    const inf = 1 << 30;
    let ans = inf;
    let s = 0;
    for (let i = 0, j = 0; j < n; ++j) {
        s += nums[j];
        while (s >= target) {
            ans = Math.min(ans, j - i + 1);
            s -= nums[i++];
        }
    }
    return ans === inf ? 0 : ans;
}

评论