C++ solution with O(n) time complexity


  • 0
    J

    O(n) time complexity

       class Solution {
        public:
            int minSubArrayLen(int s, vector<int>& nums) {
                int len=INT_MAX,start=0,sum=0;
                for(int i=0;i<nums.size();++i){
                    sum+=nums[i];
                    if(sum>=s){
                        while(start<i && sum>=s+nums[start]){
                            sum-=nums[start];
                            start++;
                        }
                        if(len>i-start+1)len=i-start+1;
                    }
                }
                if(len==INT_MAX)return 0;
                return len;
            }
        };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.