码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode] 974. 和可被 K 整除的子数组 !!!

时间:2020-05-27 23:17:46      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:public   http   etc   注意   image   div   col   code   for   

方法一:

class Solution {
    public int subarraysDivByK(int[] A, int K) {
        Map<Integer, Integer> record = new HashMap<>();
        record.put(0, 1);
        int sum = 0, ans = 0;
        for (int elem: A) {
            sum += elem;
            // 注意 Java 取模的特殊性,当被除数为负数时取模结果为负数,需要纠正
            int modulus = (sum % K + K) % K;
            int same = record.getOrDefault(modulus, 0);
            ans += same;
            record.put(modulus, same + 1);
        }
        return ans;
    }
}

技术图片

 

[LeetCode] 974. 和可被 K 整除的子数组 !!!

标签:public   http   etc   注意   image   div   col   code   for   

原文地址:https://www.cnblogs.com/doyi111/p/12977296.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!