※ 引述《pandix (麵包屌)》之銘言:
: Python code:
: class Solution:
: def subarraysDivByK(self, nums: List[int], k: int) -> int:
: count = [1] + [0]*(k-1)
: sum = res = 0
: for num in nums:
: sum += num
: res += count[sum%k]
: count[sum%k] += 1
: return res
怎麼感覺推出來好像怪怪的
nums = [-1, 2, 9], k = 2
count = [1, 0]
1.sum = -1, res += count[-1] = 0, count[-1] = 1
2.sum = 1, res += count[1] = 0, count[1] = 1
3.sum = 10, res += count[0] = 1, count[0] = 2
res = 1 但是答案為2
查了一下
靠邀阿 python 的負數索引會自己位移 = =
不然一般來說這題要對負數做特別處理
class Solution {
public int subarraysDivByK(int[] nums, int k) {
int[] mod = new int[k + 1];
mod[0] = 1;
int res = 0;
int sum = 0;
for (int num : nums) {
sum = (sum + num % k + k) % k;
res += mod[sum];
mod[sum]++;
}
return res;
}
}
偏數學的對我真的不太好想= =