/**
* Using two pointers to maintain a window
* the left pointer is used to add number to the sum,
* the right pointer is used to cut number from the sum,
* when sum >= s, save the length to record the minimum length
*/
public class Solution {
public int minSubArrayLen(int s, int[] nums) {
int left = 0, right = 0, sum = 0, len = Integer.MAX_VALUE;
while (right < nums.length) {
sum += nums[right++];
while (sum >= s) {
// note that right always 1 step ahead than the right side of the window
// while left is at the left edge of the window
// so len = right-left no need to plus 1 (*)
len = Math.min(len, right-left);
sum -= nums[left++];
}
}
return (len == Integer.MAX_VALUE) ? 0 : len;
}
}
Leetcode 209. Minimum Size Subarray Sum
最新推荐文章于 2020-01-23 23:12:52 发布