[英]I can't run all my test cases correctly, what's wrong?
Complete the divisibleSumPairs function in the editor below. 在下面的编辑器中完成divisibleSumPairs函数。 It should return the integer count of pairs meeting the criteria.
它应该返回符合条件的对的整数计数。
divisibleSumPairs has the following parameter(s): divisibleSumPairs具有以下参数:
n : the integer length of array ar n :数组ar的整数长度
ar : an array of integers ar :整数数组
k : the integer to divide the pair sum by k :将对和除以的整数
Print the number of (i, j) pairs where i < j and ar[i] + ar[j] is evenly divisible by k . 打印(i,j)对的数量,其中i <j和ar [i] + ar [j]被k整除。
I don't know what is wrong, only some cases has worked 我不知道出什么问题了,只有某些情况有效
static int divisibleSumPairs(int n, int k, int[] ar) {
int count = 0;
for (int i=0; i<n; i++){
for (int j=0; j<n; j++){
if ((ar[i]<ar[j]) && ((ar[i]+ar[j])%k)== 0){
count++;
}
}
}
return count;
}
The main problem is that you check for ar[i] < ar[j] while the problem statement says i < j : 主要问题是您在问题陈述说i <j时检查ar [i] <ar [j] :
static int divisibleSumPairs(int n, int k, int[] ar) {
int count = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if (i < j && (ar[i] + ar[j]) % k == 0) {
count++;
}
}
}
return count;
}
The algorithm can be further optimized to: 该算法可以进一步优化为:
static int divisibleSumPairs(int n, int k, int[] ar) {
int count = 0;
for (int i = 0; i < n; i++){
for (int j = i + 1; j < n; j++){
if ((ar[i] + ar[j]) % k == 0) {
count++;
}
}
}
return count;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.