leetcode 974. Subarray Sums Divisible by K 前缀和+同余定理

题目

https://leetcode.com/problems/subarray-sums-divisible-by-k/
Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.

Example 1:

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

思路

前缀和而后dp同余即可,任意范围的子数组和(i,j] = sum[j]-sum[i],我们要确保他mod K = 0,根据同余定理可知要求 sum[i] mod K == sum[j] mod K 即 sum[i] 同余 sum[j], 所以使用 hashmap 记录余数的个数,后面直接累加

源码

class Solution {
public:
    int sum[30005];
    int res = 0;
    map<int,int> m;
    int subarraysDivByK(vector<int>& A, int K) {
        if(A.size()==0)return res;
        sum[0] = 0;
        m[0] = 1;
        for(int i = 1;i <= A.size();++i){
            sum[i] = sum[i-1]+A[i-1];
            int yu = sum[i]%K;
            if(m.count(yu)==0){
                m[yu] = 1;
            }else{
                m[yu]++;
            }
            res+=(m[yu]-1);
        }
        return res;
    }
};

发表评论

电子邮件地址不会被公开。 必填项已用*标注