Given an array of n positive integers and a positive integer s, find the minimal length of a 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.
More practice:
If you have figured out the O(n) solution, try coding another solution of which the time complexity isO(n log n).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
思路:用同向双指针来解题。主指针i每次走一步,j每次走N步,i用for,j用while循环;
每次用j滑动到找到>=s的地方,更新 length,i++ 同时sum - nums[i]; T: O(N)
class Solution {
public int minSubArrayLen(int s, int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
int j = 0;
int cursum = 0;
int res = Integer.MAX_VALUE;
for(int i = 0; i < nums.length; i++) {
// move j;
while(j < nums.length && cursum < s) {
cursum += nums[j];
j++;
}
// update result;
if(cursum >= s) {
res = Math.min(res, j - i);
}
// move i;
cursum -= nums[i];
}
return res == Integer.MAX_VALUE ? 0 : res;
}
}