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的最短长度,时间复杂度O(n2)。
- 用两个指针,分别指向当前区间首尾,如果当前区间的和大于s,则更新min length。并且尝试不断右移指向首部的指针,直到当前区间的和小于s。最差情况是需要遍历两倍数组长度,时间复杂度O(n).
public int minSubArrayLen(int s, int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int res = Integer.MAX_VALUE;
int start = 0, end = 0, curSum = 0;
while (end < nums.length) {
curSum += nums[end];
end++;
while (curSum >= s) {
res = Math.min(res, end - start);
curSum -= nums[start];
start++;
}
}
return res == Integer.MAX_VALUE ? 0 : res;
}