C++, 4ms solution, o(N) time, o(1) space


  • 4
    class Solution {
    public:
    int minSubArrayLen(int s, vector<int>& nums) {
        if (nums.empty()) return 0;
        int res=INT_MAX;
        int i=0,j=0,sum=nums[0];
        
        while(j<nums.size()){
            if(sum>=s){
                res = min(res,j-i+1);
                if (res==1) return res;
                sum-=nums[i++];
            }else {
                j++;
                if (j<nums.size()) sum+=nums[j];
            }
        }
        if (res==INT_MAX) return 0;
        else return res;
    }
    };

  • 0
    L

    There is a stackoverflow, you have added nums[nums.size()] at your loop end.


  • 0

    Updated. Thanks!


Log in to reply
 

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