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的最小长度。
1、计算sum,然后找出以每一位开头的和大于等于s的长度。
public class Solution {
public int minSubArrayLen(int s, int[] nums) {
int len = nums.length;
if (len == 0){
return 0;
}
if (nums[0] >= s){
return 1;
}
int i = 0, result = 0, sum = 0;
for (; i < len; i++){
sum += nums[i];
if (sum >= s){
break;
}
}
if (i == len && sum < s){
return 0;
}
i++;
result = i;
sum -= nums[0];
for (int j = 1; j < len; j++){
while (i < len && sum < s){
sum += nums[i];
i++;
}
if (sum < s){
break;
}
result = Math.min(i - j, result);
sum -= nums[j];
}
return result;
}
}
2、还可以判断从0~len-1位,以每一位为结尾的最小的长度。
public class Solution { public int minSubArrayLen(int s, int[] nums) { if (nums.length == 0){ return 0; } int i = 0, j = 0, sum = 0, min = Integer.MAX_VALUE; while (j < nums.length){ sum += nums[j++]; while (sum >= s){ min = Math.min(min, j - i); sum -= nums[i++]; } } return min == Integer.MAX_VALUE ? 0 : min; } }
浙公网安备 33010602011771号