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

Posted

tags:

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

public class Solution {
    public boolean checkSubarraySum(int[] nums, int k) {
        if (nums == null || nums.length < 1) return false;
        int n = nums.length;
        //if (k != 0 && n >= 2 * Math.abs(k)) return true; //容斥原理[0,1,1,2,2,3,3,4,4,...,2k-1,2k-1]
       
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        map.put(0, -1); // if 0 appears in any position, except 0, return true
        int prefixSum = 0;
        for (int i = 0; i < n; i++) {
            prefixSum += nums[i];
            if (k != 0) prefixSum %= k;
            Integer pre = map.get(prefixSum);
            if (pre != null) {
                if (i - pre > 1) return true; 
            } else {
                map.put(prefixSum, i);
            }
        }
        return false;
    }
}
public class Solution {
    public boolean checkSubarraySum(int[] nums, int k) {
        if (nums == null || nums.length < 1) return false;
        int n = nums.length;
        if (k != 0 && n >= (long)2 * Math.abs(k)) return true; //容斥原理[0,1,1,2,2,3,3,4,4,...,2k-1,2k-1]
       
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        map.put(0, -1); // if 0 appears in any position, except 0, return true
        int prefixSum = 0;
        for (int i = 0; i < n; i++) {
            prefixSum += nums[i];
            if (k != 0) prefixSum %= k;
            Integer pre = map.get(prefixSum);
            if (pre != null) {
                if (i - pre > 1) return true; 
            } else {
                map.put(prefixSum, i);
            }
        }
        return false;
    }
}

以上是关于java 523.连续子阵列总和(Pigeonhole).java的主要内容,如果未能解决你的问题,请参考以下文章

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

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

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

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

leetcode No.523 连续的子数组和 java

Leetcode523. 连续的子数组和