Leetcode[209][M]Minimum Size Subarray Sum
18 Nov 2015###Task1 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).
###Python ####O(n)
class Solution(object):
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
"""
if not nums or len(nums) == 0:
return 0
if sum(nums) < s:
return 0
ret = len(nums)
start = 0
for i in range(1, len(nums) + 1):
while sum(nums[start:i]) >= s:
ret = min(ret, i - start)
start += 1
return ret
###Java
public class Solution {
public int minSubArrayLen(int s, int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int sum = 0;
int count = Integer.MAX_VALUE;
int start = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (sum >= s) {
while (sum - nums[start] >= s) {
sum -= nums[start];
start++;
}
int curCount = i - start + 1;
count = Math.min(count, curCount);
}
}
return sum >= s ? count : 0;
}
}
####O(nlog)
public class Solution {
public int minSubArrayLen(int s, int[] nums) {
if (null == nums || nums.length == 0) {
return 0;
}
int min = nums.length + 1;
int[] sum = new int[nums.length + 1];
for (int i = 0; i < nums.length; i++) {
sum[i + 1] = sum[i] + nums[i];
if (sum[i + 1] >= s) {
int left = binarySearch(sum, sum[i + 1] - s, 0, i + 1);
min = Math.min(min, i + 1 - left);
}
}
return min == nums.length + 1 ? 0 : min;
}
private int binarySearch(int[] nums, int target, int start, int end) {
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] >= target) {
end = mid;
} else {
start = mid;
}
}
if (nums[end] <= target) {
return end;
} else {
return start;
}
}
}
###Points
- why O(n)? cause i will move to the end definitedly in O(n) time while start index will move from begining to the end at maximum. So it is still linear run time.
- sums[i] is the sum of previous i elements.
- Binary search will find the left most edge of the subarray that equal or less than target