【Leetcode-209】长度最小的子数组

方法一、遍历元素,逐项寻找子数组

方法二、双指针法

i,j开始都指向0;
j开始右移,若s(i,j)的和大于等于target,则减去arr[i],i右移,直至s(i,j)小于target;
j继续右移,同样操作,直至最后;

int minSubArrayLen(int s, int *nums, int numsSize) {
    if (numsSize == 0) {
        return 0;
    }
    int ans = INT_MAX;
    int start = 0, end = 0;
    int sum = 0;
    while (end < numsSize) {
        sum += nums[end];
        while (sum >= s) {
            ans = fmin(ans, end - start + 1);
            sum -= nums[start];
            start++;
        }
        end++;
    }
    return ans == INT_MAX ? 0 : ans;
}

你可能感兴趣的:(LeetCode)