Simple CPP O(N) time O(1) space solution


  • 2
    O
    class Solution {
    public:
        int minSubArrayLen(int s, vector<int>& nums) {
            int N = nums.size();
            if (N <= 0) return 0;
            int fast = 0, slow = 0, sum = nums[0];
            int ans = INT_MAX;
            while (1) {
                if (sum < s) {
                    fast++;
                    if (fast >= N) break;
                    sum += nums[fast];
                } else {
                    ans = min(ans, fast - slow + 1);
                    if (slow >= N) break;
                    sum -= nums[slow];
                    slow++;
                }
            }
            return ans == INT_MAX ? 0 : ans;
        }
    };

Log in to reply
 

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