209. Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

For example, given the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the minimal length under the problem constraint.

S: 窗口型two pointer O(N)

    int minSubArrayLen(int s, vector<int>& nums) {
        int len = 0;
        int curSum = 0;
        int n = nums.size();
        for (int i = 0, j = 0; i < n; ++i) {
            while (j < n && curSum < s) {
                curSum += nums[j];
                j++;
            }
            if (curSum >= s && (len == 0 || len > j - i)) {
                len = j - i;
            }
            curSum -= nums[i];
        }
        return len;  
    }

results matching ""

    No results matching ""