0974.cpp (366B)
1 class Solution { 2 public: 3 int subarraysDivByK(vector<int> &nums, int k) { 4 int n = nums.size(), sum = 0, res = 0; 5 vector<int> dp(k, 0); 6 7 dp[0] = 1; 8 for (int num : nums) { 9 sum += num; 10 int rem = sum % k; 11 if (rem < 0) rem += k; 12 res += dp[rem]++; 13 } 14 return res; 15 } 16 };