Ac solution code


  • 0

    This solution is based on Sliding window.

    runtime = O(n); space = O(1)

    public int minSubArrayLen(int s, int[] nums) {
    	if (nums == null || nums.length == 0) return 0;
    	int j = 0, sum = 0;
    	int res = Integer.MAX_VALUE;
    	for (int i = 0; i < nums.length; i++) {
    		while (j < nums.length && sum < s) {// Forward right pointer j until satisfies sum >= s 
    			sum += nums[j];
    			j++;
    		}
    		if (sum >= s)// NOTE: need to verify sum >= s, because this is not guaranteed by the previous while loop 
    		    res = Math.min(res, j - i);
    		sum -= nums[i];// Forward left pointer i, and set sum = sum - nums[i]		
    	}
    	return res != Integer.MAX_VALUE ? res : 0;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.