Simple c++ solution with two points, only 14 lines, O(n) in time, O(1) in space


  • 0
    Q
    class Solution {
    public:
        int minSubArrayLen(int s, vector<int>& nums) 
        {
            int ns(0), ans(0), l(0);
            
            for (int r = 0; r < nums.size(); ++ r)
            {
                ns += nums[r];
                while (ns >= s)
                {
                    if (ans == 0 || r - l + 1 < ans)
                        ans = r - l + 1;
                    ns -= nums[l];
                    l ++;
                }
            }
            return ans;
        }
    };
    

    Enumerate the right point and it is easy to know that the left point will be incremental;


Log in to reply
 

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