LeetCode209 Minimum size subarray sum at least K(Not Fully Understand)

so now we need to return the shortest length which satified >= given s

the solution is pretty straight forward, use two pointers, and we need to maintain a global minimum length of all.

//we can't presort nums,because order matters
class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        
        if (nums == null || nums.length == 0) {
            return 0;
        }
        
        int start = 0; //two pointers
        int end = 0;
        int sum = 0;
        int minLen = Integer.MAX_VALUE;
        while (end < nums.length) {
            sum += nums[end];
            if (sum < s) {
                end++;
                continue; //so that means sum will added all the way till sum>= s
            }
            while (sum >= s) { 
                sum -= nums[start]; //start pointer will shrinker until sum<s
                start++;
            }
            minLen = Math.min(minLen, end - start + 2); //keeps record of the global minimum
            end++;
            
        }
        return minLen == Integer.MAX_VALUE? 0: minLen;
    }
}

and strangely but not suprisely, this problem can be solve in binary search. but I didn;t fully understand.

    public int minSubArrayLen(int s, int[] nums) {
        return solveNLogN(s, nums);
    }
    private int solveNLogN(int s, int[] nums) {
        int[] sums = new int[nums.length + 1];
        for (int i = 1; i < sums.length; i++) sums[i] = sums[i - 1] + nums[i - 1];
        int minLen = Integer.MAX_VALUE;
        for (int i = 0; i < sums.length; i++) {
            int end = binarySearch(i + 1, sums.length - 1, sums[i] + s, sums);
            if (end == sums.length) break;
            if (end - i < minLen) minLen = end - i;
        }
        return minLen == Integer.MAX_VALUE ? 0 : minLen;
    }
    
    private int binarySearch(int lo, int hi, int key, int[] sums) {
        while (lo <= hi) {
           int mid = (lo + hi) / 2;
           if (sums[mid] >= key){
               hi = mid - 1;
           } else {
               lo = mid + 1;
           }
        }
        return lo;
    }

posted @ 2020-05-16 14:29  EvanMeetTheWorld  阅读(17)  评论(0)    收藏  举报