LeetCode刷题实战209:长度最小的子数组
Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.
题意
示例
示例 1:
输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
示例 2:
输入:target = 4, nums = [1,4,4]
输出:1
示例 3:
输入:target = 11, nums = [1,1,1,1,1,1,1,1]
输出:0
解题
class Solution {
public int minSubArrayLen(int s, int[] nums) {
// copy from leetcode.com
if (null == nums || nums.length == 0) { return 0; }
int i = 0, j = 0;
int sum = 0, minLen = Integer.MAX_VALUE;
while (j < nums.length) {
sum += nums[j++];
if (sum < s) { continue; }
while (sum >= s) {
sum -= nums[i];
i++;
}
minLen = Math.min(minLen, j - i + 1);
}
return (minLen == Integer.MAX_VALUE) ? 0 : minLen;
}
}