Minimum Size Subarray Sum

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.

For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

#include <iostream>
#include <vector>
#include <cassert>

using namespace std;

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        assert(s>0);
        //[i...j]
        int i=0,j=-1;
        int sum=0;
        int res=nums.size()+1;


        while(i<nums.size()){
            // i<nums.size()) && (j+1<nums.size())maybe j to end,
            // "||" may i to somewhere,j out of end
            //i not
            if(j+1<nums.size() && sum<s){
                j++;
                sum+=nums[j];
            } else{
                sum-=nums[i];
                i++;

            }
            //i add judge sum
            if(sum>=s){
                res=min(res,j-i+1);
            }

        }

        if(res==nums.size()+1){
            return 0;
        }
        return res;
    }
};

int main(){
    int arr[]={2,3,1,2,4,3};
    vector<int> val(arr,arr+sizeof(arr)/sizeof(int));

    int s=7;

    int ret=Solution().minSubArrayLen(s,val);
    cout<<ret<<endl;


}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,973评论 0 33
  • Given an array of n positive integers and a positive inte...
    DrunkPian0阅读 425评论 0 0
  • 台湾某当劳拍了一个视频短片,内容是「如果我30岁还没结婚,你要娶我」,讲述的是一个万年备胎的故事…… 戳下方链接看...
    偶饰唯维阅读 1,248评论 0 1
  • 01 我和张扬相遇就是这么平凡寡淡,经由大学同学介绍我结识了总穿格子衬衫的他。 张扬是典型的理工男,黑色边框眼镜,...
    九歌_阅读 2,311评论 35 40
  • 那一次离开济南,想想那混黑的天,呛得行人来往匆匆,全身远看是黑影,走近只剩一双眼在朦胧里探寻前方。看着空间动态对天...
    核桃银杏阅读 261评论 0 0

友情链接更多精彩内容