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. 和可被 K 整除的子数组 #23

Open
zpc7 opened this issue Aug 7, 2022 · 0 comments
Open

974. 和可被 K 整除的子数组 #23

zpc7 opened this issue Aug 7, 2022 · 0 comments
Labels
中等 LeetCode 难度定级

Comments

@zpc7
Copy link
Owner

zpc7 commented Aug 7, 2022

974. 和可被 K 整除的子数组

参考题解: https://leetcode.cn/problems/subarray-sums-divisible-by-k/solution/you-jian-qian-zhui-he-na-jiu-zai-ci-dai-ni-da-tong/

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
function subarraysDivByK(nums, k) {

  let preSumModK = 0; // 前缀和模除

  let count = 0; // 将要返回的数目

  const map = { 0: 1 };

  for (let i = 0; i < nums.length; i++) {
    preSumModK = (preSumModK + nums[i]) % k; // 递推式子

    if (preSumModK < 0) {
      preSumModK += k;
    }


    if (map[preSumModK]) {      // 已经存在于map
      count = count + map[preSumModK]; // 把对应的次数累加给count(在这里处理count 说明 子数组和 是K的倍数, 那么必然存在能整除的子数组)
      map[preSumModK]++;        // 并且更新出现次数,次数+1
    } else {
      map[preSumModK] = 1;      // 之前没出现过,初始化值为1
    }
  }
  return count;
};
@zpc7 zpc7 added 中等 LeetCode 难度定级 JS and removed JS labels Aug 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
中等 LeetCode 难度定级
Projects
None yet
Development

No branches or pull requests

1 participant