forked from havanagrawal/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_974.java
34 lines (28 loc) · 844 Bytes
/
_974.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.fishercoder.solutions;
import java.util.HashMap;
import java.util.Map;
/**
* 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.
* */
public class _974 {
public static class Solution1 {
public int subarraysDivByK(int[] A, int K) {
int count = 0;
int sum = 0;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
for (int i = 0; i < A.length; i++) {
sum = (sum + A[i]) % K;
if (sum < 0) {
sum += K;
}
count += map.getOrDefault(sum, 0);
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
return count;
}
}
}