[leetcode]974. Subarray Sums Divisible by K

[leetcode]974. Subarray Sums Divisible by K


Analysis

努力工作哇—— [每天刷题并不难0.0]

Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.
在这里插入图片描述

Explanation:

https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/217985/JavaC%2B%2B-Count-the-Remainder
The key point is :we just have to see if running total mod k is equal to any previous running total mod k

Implement

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

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/87889352