Minimum Size Subarray Sum

原题地址:https://leetcode.com/problems/minimum-size-subarray-sum/#/description

题目:
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous 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.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

思路:
首先intuitive的想法是double foo loop。但是可以用双指针加sliding window的思想,设sum和min两个变量。红色部分是当条件改为sum == s时候的解法。link for array with negative element: http://www.geeksforgeeks.org/find-subarray-with-given-sum-in-array-of-integers/  (use a map to store the sum from the first element to each i'th element).

follow up:
关于2D array解法的链接:http://blog.csdn.net/sjphichina/article/details/52237277。


代码:

public int minSubArrayLen(int s, int[] nums) {
    if(nums == null || nums.length == 0){
        return 0;
    }
    int fast = 0;
    int slow = 0;
    int sum = 0;
    int min = Integer.MAX_VALUE;
    while(fast <= nums.length - 1){
        sum += nums[fast];
        fast++;
        while(sum >= s){
                if(sum == s){
                    min = Math.min(min, fast - slow);
                }
                sum -= nums[slow];
                slow++;
            }
    }
    return min == Integer.MAX_VALUE ? 0 : min;
}





Comments

Popular Posts