实现代码:
public class Solution {
public int MinSubArrayLen(int s, int[] nums)
{
int? min = null;
for(var i = 0;i < nums.Length; i++){
var l = MinLen(nums, i, s);
if(l.HasValue && l < min || min == null){
min = l;
}
}
return min.HasValue ? min.Value : 0;
}
private int? MinLen(int[] nums, int start, int target)
{
var s = 0;
var startFrom = start;
while(start < nums.Length){
s += nums[start];
if(s >= target){
return (start - startFrom + 1);
}
start ++;
}
return null;
}
}
public class Solution {
public int MinSubArrayLen(int s, int[] nums)
{
var len = nums.Length;
var sum = 0;
int? min = null;
// use two pointers
var start = 0;
var end = 0;
while (end < len)
{
// if current sum if smaller , keep moving right pointer forward
while (sum < s && end < len){
sum += nums[end];
end ++;
}
// if sum is more than target, keep moving left pointer forward to shrink the window size
while (sum >= s)
{
// find a smaller window then update size
if (!min.HasValue || end - start < min){
min = end - start;
}
// unload left most value from sum
sum -= nums[start];
start ++;
}
// now sum less than target again
// lets play again with the right pointer if not yet reach the end
}
return !min.HasValue ? 0 : min.Value;
}
}
LeetCode -- Minimum Size Subarray Sum
原文:http://blog.csdn.net/lan_liang/article/details/49962379