LeetCode:Minimum Size Subarray Sum

22 篇文章 0 订阅
15 篇文章 0 订阅

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). 

题目的意思是给一个包含n个全部都是正数的数组和一个正数s,找到最小的子数组,这个子数组呢,一些元素的和呢要大于等于s.比如:【1,2,1,3,4,6,5】和为9,那么有两个子数组包含和为9,【2,1,3,4】和【4,6,5】一个长度为4一个长度为3所以返回3。刚开始一直没有理解题意。理解题意,那么O(n)的解题方法很简单,滑动窗口就可以了,然后在这个过程中记录值长度最小的值就可以了。

还是以【1,2,1,3,4,6,5】和9为例。分别用left和right记录滑动窗口的两端。刚开始left=0,right=0,窗口大小为0,所以增大right,当然right的值要小于数组的长度。这个时候sum+=nums[right].如果sum>=s而且还没有到达边界。这个时候记录下该窗口大小的值。然后将窗口变小,直到和小于s为止。然后继续向后滑动,直到结束为止。代码如下:

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {                
        if(nums.empty()){
            return  0;
        }
        int n=nums.size();
        int left=0,right=0,minLen=n+1,sum=0;
        while(right<n){    //窗口不能超出右边界
            while(sum<s && right<n ){  //向右扩大窗口,直到大于s为止。
                sum+=nums[right++];
            }
            while(sum>=s){
                minLen=min(minLen,right-left);   //比较当前窗口的大小。
                sum-=nums[left++];               //缩小窗口
            }
        }
        return minLen==n+1?0:minLen;
    }
};

另一种

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值