您的位置:首页 > 其它

算法系列——Minimum Size Subarray Sum

2017-08-10 21:17 253 查看

题目描述

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.

解题思路

双指针+滑动窗口

双指针 l,r 维护当前序列和>=s的区间,然后更新区间最小值。

算法实现

public class Solution {
public int minSubArrayLen(int s, int[] nums) {
int l=0,r=-1;
int sum=0;
int result=nums.length+1;
while(l<nums.length){
if(r+1<nums.length&&sum<s)
sum+=nums[++r];
else
sum-=nums[l++];
if(sum>=s)
result=Math.min(result,r-l+1);
}
if(result==nums.length+1)
return 0;
return result;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: