LeetCode刷题实战209:长度最小的子数组

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 长度最小的子数组,我们先来看题面:

https://leetcode-cn.com/problems/minimum-size-subarray-sum/

Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.

题意

给定一个含有 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

解题

思路分析:

连续子数组,考虑使用双指针start与end滑动窗口来判断.设置一个sum值,表示滑动窗口中的和,每一轮循环,判断sum与s的关系,有两种情况:

sum大于等于s,此时sum减去start指针所指向的值,start指针前进。

sum小于s,此时,sum加上end的值,end指针前进。

class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        // copy from leetcode.com
        if (null == nums || nums.length == 0) { return 0; }
        int i = 0, j = 0;
        int sum = 0, minLen = Integer.MAX_VALUE;
        while (j < nums.length) {
            sum += nums[j++];
            if (sum < s) { continue; }
            while (sum >= s) {
                sum -= nums[i];
                i++;
            }
            minLen = Math.min(minLen, j - i + 1);
        }
        return (minLen == Integer.MAX_VALUE) ? 0 : minLen;

    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-200题汇总,希望对你有点帮助!

LeetCode刷题实战201:数字范围按位与

LeetCode刷题实战202:快乐数

LeetCode刷题实战203:移除链表元素

LeetCode刷题实战204:计数质数

LeetCode刷题实战205:同构字符串

LeetCode刷题实战206:反转链表

LeetCode刷题实战207:课程表

LeetCode刷题实战208:实现 Trie (前缀树)

LeetCode刷题实战209:长度最小的子数组_第1张图片

你可能感兴趣的:(算法,链表,指针,toolbar,leetcode)