资讯专栏INFORMATION COLUMN

[LeetCode] 209. Minimum Size Subarray Sum (Easy ve

HelKyle / 1372人阅读

Problem

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn"t one, return 0 instead.

Example:

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

Solution
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        int i = 0, j = 0, sum = 0, min = Integer.MAX_VALUE;
        
        while (i <= j && j < nums.length) {
            sum += nums[j];
            while (sum >= target && i <= j) {
                min = Math.min(min, j-i+1);
                sum -= nums[i];
                i++;
            }
            j++;
        }
        
        return min == Integer.MAX_VALUE ? 0 : min;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72432.html

相关文章

  • LeetCode 209:最小长度的子数组 Minimum Size Subarray Sum

    摘要:如果不存在符合条件的连续子数组,返回。示例输入输出解释子数组是该条件下的长度最小的连续子数组。截取从索引到索引的数组,该数组之和若小于,则继续后移,直到大于等于。记录与差值返回的目标数。之后后移一位继续刷新新数组。 公众号: 爱写bug(ID:icodebugs)作者:爱写bug 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组...

    jas0n 评论0 收藏0
  • LeetCode 209:最小长度的子数组 Minimum Size Subarray Sum

    摘要:如果不存在符合条件的连续子数组,返回。示例输入输出解释子数组是该条件下的长度最小的连续子数组。截取从索引到索引的数组,该数组之和若小于,则继续后移,直到大于等于。记录与差值返回的目标数。之后后移一位继续刷新新数组。 公众号: 爱写bug(ID:icodebugs)作者:爱写bug 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组...

    JayChen 评论0 收藏0
  • LeetCode 209:最小长度的子数组 Minimum Size Subarray Sum

    摘要:如果不存在符合条件的连续子数组,返回。示例输入输出解释子数组是该条件下的长度最小的连续子数组。截取从索引到索引的数组,该数组之和若小于,则继续后移,直到大于等于。记录与差值返回的目标数。之后后移一位继续刷新新数组。 算法是一个程序的灵魂 公众号:爱写bug(ID:icodebugs)作者:爱写bug 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的...

    wow_worktile 评论0 收藏0
  • LeetCode 209:最小长度的子数组 Minimum Size Subarray Sum

    摘要:如果不存在符合条件的连续子数组,返回。示例输入输出解释子数组是该条件下的长度最小的连续子数组。截取从索引到索引的数组,该数组之和若小于,则继续后移,直到大于等于。记录与差值返回的目标数。之后后移一位继续刷新新数组。 算法是一个程序的灵魂 公众号:爱写bug(ID:icodebugs)作者:爱写bug 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的...

    Vixb 评论0 收藏0
  • [Leetcode] Minimum Size Subarray Sum 最短子串和

    摘要:双指针复杂度时间空间思路我们用两个指针维护一个窗口,保证这个窗口的内的和是小于目标数的。如果和仍小于目标数,则将窗口右边界右移。另外,如果左边界大于右边界时,说明最短子串的长度已经小于等于,我们就不用再查找了。 Minimum Size Subarray Sum Given an array of n positive integers and a positive integer ...

    wthee 评论0 收藏0

发表评论

0条评论

HelKyle

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<