Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

974. Subarray Sums Divisible by K #181

Open
Tcdian opened this issue May 27, 2020 · 1 comment
Open

974. Subarray Sums Divisible by K #181

Tcdian opened this issue May 27, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented May 27, 2020

974. Subarray Sums Divisible by K

给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续、非空)子数组的数目。

Example

Input: A = [4,5,0,-2,-3,1], K = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by K = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]

Note

  • 1 <= A.length <= 30000
  • -10000 <= A[i] <= 10000
  • 2 <= K <= 10000
@Tcdian
Copy link
Owner Author

Tcdian commented May 27, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[]} A
 * @param {number} K
 * @return {number}
 */
var subarraysDivByK = function(A, K) {
    let prefix = 0;
    const cache = new Map([[prefix, 1]]);
    let result = 0;
    for (let i = 0; i < A.length; i++) {
        prefix += A[i];
        while(prefix < 0) {
            prefix += K;
        }
        if (cache.has(prefix % K)) {
            result += cache.get(prefix % K);
        }
        cache.set(prefix % K, (cache.get(prefix % K) || 0) + 1);
    }
    return result;
};
  • TypeScript Solution
var subarraysDivByK = function(A: number[], K: number): number {
    let prefix = 0;
    const cache = new Map([[prefix, 1]]);
    let result = 0;
    for (let i = 0; i < A.length; i++) {
        prefix += A[i];
        while(prefix < 0) {
            prefix += K;
        }
        if (cache.has(prefix % K)) {
            result += cache.get(prefix % K) as number;
        }
        cache.set(prefix % K, (cache.get(prefix % K) || 0) + 1);
    }
    return result;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant