您的位置:首页 > 其它

Leetcode: Minimum Size Subarray Sum

2015-12-17 06:52 459 查看
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.

click to show more practice.

More practice:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).


Haven't think about the O(nlogn) solution.

O(n) solution is to maintain a window

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


Initially I'm concerning I should maintain the window to have its sum always be >= s, and l should always fall at a place maintaining this property. But the solution above proves that I need not do this. Anyway, my solution also works as follows:

public class Solution {
public int minSubArrayLen(int s, int[] nums) {
int minWin = Integer.MAX_VALUE;
int l=0, r=0;
if (nums==null || nums.length==0) return 0;
int sum = 0;
while (r < nums.length) {
sum += nums[r];
if (sum >= s) { //found one feasible window, try to shrink the window
while (l<=r && sum-nums[l] >= s) {
sum -= nums[l++];
}
minWin = Math.min(minWin, r-l+1);
}
r++;
}
if (r==nums.length && l==0 && sum<s) return 0;
return minWin;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: