Share my C++ solution,easy to understand


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

Log in to reply
 

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