每日一练(45):长度最小的子数组

简介: 给定一个含有 n 个正整数的数组和一个正整数 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


来源:力扣(LeetCode)


链接:https://leetcode-cn.com/probl...


方法一:队列模拟滑动窗口


思路分析


使用队列模拟滑动窗口,并使用一个sum记录队列内数的和,由于数的大小有别,所以这里使用while来推出队列中的数


int minSubArrayLen(int target, vector<int>& nums) {
    int ans = INT_MAX, sum = 0;
    queue<int> que;
    for (auto &n : nums) {
        sum += n;
        que.push(n);
        while (sum >= target) {
            ans > que.size() ? ans = que.size() : ans;
            sum -= que.front();
            que.pop();
        }
    }
    return ans == INT_MAX ? 0 : ans;
}


方法二:双指针


思路分析


定义两个指针i和j指针,将区间[j,i]看成滑动窗口,那么两个指针就分别表示滑动窗口的开始位置和结束位置,同时我们再维护一个sum变量用来存贮区间[j,i]连续数组的和。如果当前滑动窗口维护的区间和sum大于等于target,就说明当前的窗口是可行的,可行中的长度最短的滑动窗口就是答案


int minSubArrayLen(int target, vector<int>& nums) {
    int res = INT_MAX, sum = 0;
    for (int i = 0, j = 0; i < nums.size(); i++) {
        sum += nums[i];//向右扩展窗口
        while (sum - nums[j] >= target) {//向左收缩窗口
            sum -= nums[j++];
        } 
        if (sum >= target) {//区间更新
            res = min(res, i - j + 1);
        }
    }
    return res == INT_MAX ? 0 : res;
}


目录
相关文章
|
4月前
|
Java C++ Python
leetcode-209:长度最小的子数组
leetcode-209:长度最小的子数组
23 0
|
3月前
|
算法
|
20天前
【力扣】209. 长度最小的子数组
【力扣】209. 长度最小的子数组
|
28天前
|
算法 测试技术
每日一题:LeetCode-209. 长度最小的子数组(滑动窗口)
每日一题:LeetCode-209. 长度最小的子数组(滑动窗口)
|
4月前
|
算法
算法题解-长度最小的子数组
算法题解-长度最小的子数组
|
11月前
每日一题——长度最小的子数组
每日一题——长度最小的子数组
|
11月前
图解LeetCode——209. 长度最小的子数组
图解LeetCode——209. 长度最小的子数组
43 1
图解LeetCode——209. 长度最小的子数组
每日一题:Leetcode209 长度最小的子数组
每日一题:Leetcode209 长度最小的子数组
|
算法
LeetCode:209. 长度最小的子数组
题目描述:给定一个含有 n 个正整数的数组和一个正整数 target 。 找出该数组中满足其和≥ target的长度最小的连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回0。
leetcode 209 长度最小的子数组
leetcode 209 长度最小的子数组
64 0