Python 对所有和可被k整除的子数组进行计数
当我在为采访而学习时,我在Geeksforgek上发现了这个问题和解决方案,但我不理解这个解决方案 上面说的是Python 对所有和可被k整除的子数组进行计数,python,algorithm,Python,Algorithm,当我在为采访而学习时,我在Geeksforgek上发现了这个问题和解决方案,但我不理解这个解决方案 上面说的是 Let there be a subarray (i, j) whose sum is divisible by k sum(i, j) = sum(0, j) - sum(0, i-1) 任何子阵列的总和都可以写成q*k+rem,其中q是a 商和rem是余数 我们看到,对于sumi,j,即任何子数组的和是 可被k整除,RHS也应可被k整除。 q1-q2k显然可以被k整除,对于r
Let there be a subarray (i, j) whose sum is divisible by k
sum(i, j) = sum(0, j) - sum(0, i-1)
任何子阵列的总和都可以写成q*k+rem,其中q是a
商和rem是余数
我们看到,对于sumi,j,即任何子数组的和是
可被k整除,RHS也应可被k整除。
q1-q2k显然可以被k整除,对于rem1-rem2到
遵循相同的公式,rem1=rem2,其中
首先,我不明白q1和q2的意思
def subCount(arr, n, k):
# create auxiliary hash
# array to count frequency
# of remainders
mod =[]
for i in range(k + 1):
mod.append(0)
cumSum = 0
for i in range(n):
cumSum = cumSum + arr[i]
mod[((cumSum % k)+k)% k]= mod[((cumSum % k)+k)% k] + 1
result = 0 # Initialize result
# Traverse mod[]
for i in range(k):
if (mod[i] > 1):
result = result + (mod[i]*(mod[i]-1))//2
result = result + mod[0]
return result
在这个解决方案代码中,我没有mod的角色。增加累积数%k+k%kth数组的值有什么效果
如果能简单地一步一步地解释,那就太好了。谢谢 您熟悉整数模/余数运算吗
7 modulo 3 = 1 because
7 = 2 * 3 + 1
compare
N % M = r
because N might be represented as
N = q * M + r
here r is remainder and q is result of integer division like
7 // 3 = 2
对于模k,可能有k个不同的余数0..k-1
mod数组包含每个可能余数的计数器。当计算每个子范围和的余数时,相应的计数器将递增,因此生成的mod数组数据看起来像[3,2,5,0,7]三个零余数,两个余数等于1
def subCount(arr, n, k):
# create auxiliary hash
# array to count frequency
# of remainders
mod =[]
for i in range(k + 1):
mod.append(0)
cumSum = 0
for i in range(n):
cumSum = cumSum + arr[i]
mod[((cumSum % k)+k)% k]= mod[((cumSum % k)+k)% k] + 1
result = 0 # Initialize result
# Traverse mod[]
for i in range(k):
if (mod[i] > 1):
result = result + (mod[i]*(mod[i]-1))//2
result = result + mod[0]
return result
7 modulo 3 = 1 because
7 = 2 * 3 + 1
compare
N % M = r
because N might be represented as
N = q * M + r
here r is remainder and q is result of integer division like
7 // 3 = 2