Sunday, January 22, 2017

Leetcode/F家 -- 209. Minimum Size Subarray Sum(window: two ptr)

209. Minimum Size Subarray Sum(window two ptr)
Medium
https://leetcode.com/problems/minimum-size-subarray-sum/
相关题: http://rainykat.blogspot.com/2017/01/leetcode-76-minimum-window-substring.html
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.
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).

思路: 2 pointers. i is the start of subarray, j is end, keep tracking min of len = j-i +1;
          Outerloop: j<nums.length Since keep a window [i,j] subarray end at j,
          Innerloop: while(sum>=s) keep subtracting i, update len is min


public int minSubArrayLen(int s, int[] nums) {
        int len = nums.length + 1;//any max value to be overwrite
        int i = 0, j = 0;
        int sum = 0;
        while(j < nums.length){//find min subarray[i,j]
            sum += nums[j];
            while(sum >= s){
                len = Math.min(len, j - i + 1);//i is valid at this point
                sum -= nums[i];
                i++;
            }
            j++;
        }
        return len == nums.length + 1 ? 0:len;
    }

No comments:

Post a Comment