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

Posted xgbt

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了974. 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]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subarray-sums-divisible-by-k

1.负数求余
Sum = ((Sum % Mod) + Mod) % Mod;
2.同余定理应用
子数组和能否被K整除 转化为
(preSum[j] - preSum[i-1]) mod K == 0
根据同余定理,转化为
preSum[j] mod K == preSum[i-1] mod K

class Solution {
public:
    int subarraysDivByK(vector<int>& A, int K) {
        map <int,int> Map = {{0 , 1}};  //预置边界情况,第0项为1 
        int ans = 0;
        int preSum = 0;
        for (int elem: A){
            preSum += elem;
            preSum = ((preSum % K) + K) % K;     //负数取模的处理
            ans += Map[preSum];
            Map[preSum]++;
        }

        return ans;
    }
};










以上是关于974. Subarray Sums Divisible by K. 前缀和同余定理的主要内容,如果未能解决你的问题,请参考以下文章

leetcode974. Subarray Sums Divisible by K

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

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

Leetcode 974. Subarray Sums Divisible by K

最大子段和DP前缀和C. Increase Subarray Sums

最大子段和DP前缀和C. Increase Subarray Sums