leetcode974-和可被K整除的子数组

原题

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

示例:

输入: A = [4,5,0,-2,-3,1], K = 5
输出: 7
解释:
有 7 个子数组满足其元素之和可被 K = 5 整除:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]

提示:

  1. 1 <= A.length <= 30000
  2. -10000 <= A[i] <= 10000
  3. 2 <= K <= 10000

解法

思想

看到连续的子数组的和就要想到前缀和

代码

class Solution {
    public int subarraysDivByK(int[] A, int K) {
        int[] remainder = new int[K];
        remainder[0] = 1;
        int sum = 0;
        int count = 0;
        for(int i = 0;i<A.length;i++){
            sum += A[i];
            int remain = sum%K;
            if(remain<0) remain += K;
            count += remainder[remain];
            remainder[remain]++;
        }
        return count;
    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode974-%e5%92%8c%e5%8f%af%e8%a2%abk%e6%95%b4%e9%99%a4%e7%9a%84%e5%ad%90%e6%95%b0%e7%bb%84/

发表评论

电子邮件地址不会被公开。