974. Subarray Sums Divisible by K解题报告

Description:

image.png

Link:

https://leetcode.com/problems/subarray-sums-divisible-by-k/

解题方法:

If Sum[0 to i] % K == Sum[0 to j] and i < j, then Sum[i + 1 to j] % K == 0, so each time we find out an existing mod result, it means we find out a sub-array which sum of this sub-array is divisible by K. Then we can use a hash map to save the count of each mod result. But how can we get the total count of this kinda sub-arrays? For example:
We have a mod result 4 has been happened a bunch of time.
Let's say, we got mod result 4 at index i, j , k, l:
At second time we got 4 at j, which mean, the subarray[i + 1, j] is what we are looking for.
At third time we got 4 at k, subarray[j + 1, k] is what we are looking for, but subarray[i + 1, k] is also the subarray with sum is divisible by K. So at this point we actually find out hash[4] - 1 subarrays.

Tips:

C++ allows a % b and a < 0, but python not.

Time Complexity:

O(n)

完整代码:

class Solution {
public:
    int subarraysDivByK(vector<int>& A, int K) {
        if(!K || A.size() == 0)
            return 0;
        unordered_map<int, int> hash;
        hash[0] = 1;
        int mod = 0, ans = 0, sum = 0;
        for(int i = 0; i < A.size(); i++) {
            sum += A[i];
            while(sum < 0)
                sum += K;
            mod = sum % K;
            if(hash.find(mod) != hash.end()) {
                ans += hash[mod];
            }
            hash[mod]++;
        }
        return ans;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,499评论 0 10
  • 育儿先育己,要学习的知识还不少! 给孩子的未来脑计划,讲到的科学理论,都是对育儿方面的具体实践,能够在育儿的过程中...
    成长开发者阅读 124评论 0 0
  • 好像好久没这么晚睡了,忙忙叨叨一天。晚上小家伙十点半才睡,我跟着也眯着了。突然想起有课件没做,立马打鸡血一样起来开...
    漫漫无忧阅读 329评论 9 7
  • 明天要进行统计学期末考试,大家都在复习统计学,都达到了肝肠寸断的地步。大家都很重视这门课程,因为如果挂科了...
    侃侃我阅读 330评论 0 0
  • 昨是今非人犹在,斗转星移水空流。 人面湖光相映好,杨柳依依鸟空啼。
    不明白的我阅读 331评论 2 0