leetcode 974. 和可被 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 <= A.length <= 30000
  • -10000 <= A[i] <= 10000
  • 2 <= K <= 10000

解法:

class Solution {
public:
    int subarraysDivByK(vector<int>& A, int K) {
        vector<int> mp(K, 0);
        mp[0] = 1;
        int pre = 0;
        int res = 0;
        for(int val : A){
            pre += val;
            pre %= K;
            if(pre < 0){
                pre += K;
            }
            res += mp[pre];
            mp[pre]++;
        }
        return res;
    }

    int subarraysDivByK2(vector<int>& A, int K) {
        unordered_map<int, int> mp;
        int pre = 0;
        mp[0] = 1;
        int res = 0;
        for(int val : A){
            pre += val;
            for(auto it : mp){
                if((pre - it.first) % K == 0){
                    res += it.second;
                }
            }
            if(mp.find(pre) != mp.end()){
                mp[pre]++;
            }else{
                mp[pre] = 1;
            }
        }
        return res;
    }
};
上一篇:Python datetime模块简单记录


下一篇:leetcode 974 Subarray Sums Divisible by K