您的位置:首页 > 其它

LeetCode Minimum Size Subarray Sum

2015-11-12 23:03 387 查看
Description:

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.
Solution:
Two pointers

Very similar to sliding window.

import java.io.*;
import java.util.*;

/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/

class Solution {
public int minSubArrayLen(int s, int[] nums) {
if(nums==null)
return 0;
int length = nums.length;
int min = length+1;

int left = 0, right = 0;
int sum = 0;
while(right<length){
if(sum+nums[right]<s){
sum+= nums[right];
right++;
} else {
min = Math.min(min, right-left+1);
sum -= nums[left];
left++;
}
}

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