Question:
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.
Tips:
给定一个长度为n的正整数数组,以及一个正整数s。找到长度最小的连续子数组,使他们的和大于等于s,并返回子数组的长度。如果不存在这样的子数组,就返回0.
思路:
设置两个变量,slow记录子数组的第一个数字位置,fast记录子数组当前要加到sum的数字位置。
fast从0位置开始向后移动,每次都加入到sum中sum+=nums[fast++];
当sum>=s时,最终结果ans就取原来的ans与fast-slow+1之间的最小值。在对sum进行减操作,减掉nums[slow],并继续判断sum是否仍然大于等于s。如果扔>=,slow向前移动,继续减nums[slow],
否则再继续在sum上加nums[fast]。
代码:
public int minSubArrayLen(int s, int[] nums) {
if(nums==null || nums.length<=0) return 0;
int len=nums.length;
int ans=Integer.MAX_VALUE;
int slow=0,fast=0;
int sum=0;
while(fast<len){
sum+=nums[fast++];
while(sum>=s){
//前面sum与nums[fast++]相加,fast也自加了1,所以比较min与fast-slow即可
ans=Math.min(fast-slow,ans);
sum-=nums[slow++];
if(sum==0)return 1;//代表刚减掉的nums[slow]=s
}
}
return ans==Integer.MAX_VALUE?0:ans;
}