您的位置:首页 > 编程语言 > Java开发

Minimum Size Subarray Sum 【leetCode】Java

2015-06-01 11:01 260 查看
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.

这道题有两种解法。

第一种是双指针的方法,维持一个窗口,然后向右滑动。程序如下,有点乱,有时间在回来整理吧。。

public int minSubArrayLen(int s, int[] nums) {
int rst=0;
if(nums==null||nums.length==0)
return rst;
int len=nums.length;
int left=0;
int right=0;
int sum=0;
while(right<len&&sum<s){
sum+=nums[right];
right++;
}
if(sum<s){
return rst;
}
right--;
rst=right-left+1;

while(left<=right&&right<len){
if(sum-nums[left]>=s){
sum-=nums[left];
left++;
rst=Math.min(rst, right-left+1);
}else if(right<len-1){
right++;
sum+=nums[right];
}else {
break;
}

}
return rst;
}


另一种方法思路可以参考:/article/4901757.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: