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
the subarray
[2,3,1,2,4,3] and s = 7,the subarray
[4,3] has the minimal length under the problem constraint.
用滑动窗口的做法
public class Solution {
public int minSubArrayLen(int s, int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int left = 0;
int right = 0;
int sum = 0;
int min = Integer.MAX_VALUE;
while (right < nums.length) {
sum += nums[right];
while (sum >= s) {
sum -= nums[left];
min = Math.min(min, right - left + 1);
left++;
}
right++;
}
if (min == Integer.MAX_VALUE) {
return 0;
} else {
return min;
}
}
}
没有评论:
发表评论