Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode 209. 长度最小的子数组 #80

Open
Chocolate1999 opened this issue Oct 8, 2020 · 0 comments
Open

LeetCode 209. 长度最小的子数组 #80

Chocolate1999 opened this issue Oct 8, 2020 · 0 comments
Labels
双指针 双指针经典题

Comments

@Chocolate1999
Copy link
Owner

仰望星空的人,不应该被嘲笑

题目描述

给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。

示例:

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

进阶:

  • 如果你已经完成了 O(n) 时间复杂度的解法, 请尝试 O(n log n) 时间复杂度的解法。

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

解题思路

滑动窗口,利用双指针实现,从左到右看,满足条件就把左指针左移,找到最小的长度,然后每次窗口右指针都往右滑动,直到数组末尾。

/**
 * @param {number} s
 * @param {number[]} nums
 * @return {number}
 */
var minSubArrayLen = function (s, nums) {
    let len = nums.length;
    let L = 0, R = 0;
    let res = Infinity, sum = 0;
    while (R < len) {
        sum += nums[R];
        while (sum >= s) { // 滑动窗口
            res = Math.min(res, R - L + 1);
            sum -= nums[L];
            L++;
        }
        R++;
    }
    return res == Infinity ? 0 : res; // 判断合法性
};

最后

文章产出不易,还望各位小伙伴们支持一波!

往期精选:

小狮子前端の笔记仓库

leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)

小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!

访问超逸の博客,方便小伙伴阅读玩耍~

学如逆水行舟,不进则退
@Chocolate1999 Chocolate1999 added the 双指针 双指针经典题 label Oct 8, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
双指针 双指针经典题
Projects
None yet
Development

No branches or pull requests

1 participant