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]
Note:
- 1 <= A.length <= 30000
- -10000 <= A[i] <= 10000
- 2 <= K <= 10000
方法1: hash table
思路:
仍然是presum + hash table来解决subarray sum问题的思路,由于这里允许负数存在,注意c++里默认的 % 计算法则:
in c++ default:
(-7/3) => -2
-2 * 3 => -6
so a%b => -1
(7/-3) => -2
-2 * -3 => 6
so a%b => 1
首先想我们需要什么养的结果?只要是相差k,-k,都应该被map到同一个结果上去,也就是说4 % 5 = 4, -1 % 5 = 4是我们想要的样子。但是by default,4 % 5 = 4, -1 % 5 = -1。所以才有了((sum % K) < 0 ? K : 0) + sum % K 这种操作。
class Solution {
public:
int subarraysDivByK(vector<int>& A, int K) {
unordered_map<int, int> hash;
hash[0] = 1;
int sum = 0, res = 0;
for (int num: A) {
sum += num;
res += hash[((sum % K) < 0 ? K : 0) + sum % K];
hash[((sum % K) < 0 ? K : 0) + sum % K]++;
}
return res;
}
};