java 209.最小尺寸子阵列总和(#)。java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 209.最小尺寸子阵列总和(#)。java相关的知识,希望对你有一定的参考价值。

public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        return solveNLogN(s, nums);
    }
    
    private int solveN(int s, int[] nums) {
        int start = 0, end = 0, sum = 0, minLen = Integer.MAX_VALUE;
        while (end < nums.length) {
            while (end < nums.length && sum < s) sum += nums[end++];
            if (sum < s) break;
            while (start < end && sum >= s) sum -= nums[start++];
            if (end - start + 1 < minLen) minLen = end - start + 1;
        }
        return minLen == Integer.MAX_VALUE ? 0 : minLen;
    }

    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;
    }
}
/*Sliding Window*/
public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        if (nums == null || nums.length < 1) return 0;
        int start = 0;
        int len = nums.length;
        int sum = 0;
        int res = len + 1;
        for (int end = 0; end < len; end++) {
            sum += nums[end];
            while (sum >= s) {
                res = Math.min(res, end - start + 1);
                sum -= nums[start++];
            }
        }
        return res == len + 1 ? 0 : res;
    }
}

以上是关于java 209.最小尺寸子阵列总和(#)。java的主要内容,如果未能解决你的问题,请参考以下文章

java 209.最小尺寸子阵列总和(#)。java

java 209.最小尺寸子阵列总和(#)。java

java 209.最小尺寸子阵列总和(#)。java

java 209.最小尺寸子阵列总和(#)。java

java 得到最小总和的子阵列

java 523.连续子阵列总和(Pigeonhole).java