简体   繁体   English

我无法正确运行所有测试用例,怎么了?

[英]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 <jar [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.

相关问题 我不能列出我所有的质数。 怎么了? :S - I can;t get all my prime numbers listed out. What's wrong? :S 我运行这个 junit 测试,但它失败了怎么回事? - I run this junit test, but it fails what's wrong? 如何使用 testng 对列表中的所有数据运行相同的测试用例? - How can I run the same test cases for all the data in a list using testng? 当所有测试用例运行时,我的测试用例失败。 但是单独跑的时候通过 - My test cases fail when all test cases are run. But passing when ran individually 如何使用jsp运行测试用例(用junit 3.x和4.x编写)? - How can I run my test cases (which written in junit 3.x and 4.x) using jsp? 我不知道怎么了,我的逻辑似乎正确 - I can't figure out what's wrong, my logic seems correct 我无法弄清楚我的NullPointerException有什么问题或者为什么它甚至存在 - I can't figure out what's wrong with my NullPointerException or why it even exists 我找不到我的 sql 语法有什么问题 - I can't find out what's wrong with my sql syntax 我的逻辑有什么问题,我无法确定从网格的左侧还是底部连续有3个? - What's wrong with my logic, I can't determine if there are 3 in a row from the left or the bottom of the grid? 无法弄清楚我的DocumentFilter有什么问题 - Can't figure out what's wrong with my DocumentFilter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM