【发布时间】:2022-01-18 19:01:25
【问题描述】:
试图用这个来夸大算法开发:
You are given an array of integers a and an integer k. Your task is to calculate the number of ways to pick two different indices i < j, such that a[i] + a[j] is divisible by k.
Example
For a = [1, 2, 3, 4, 5] and k = 3, the output should be solution(a, k) = 4.
这是我的 java 解决方案:
long solution(int[] a, int k) {
final BiPredicate<Integer, Integer> isDivisible = (x,y) -> (a[x] + a[y]) % k == 0;
long counter = 0;
for(int i = 0; i < a.length - 1; i++) {
for(int j = i + 1; j < a.length; j++ ){
if(isDivisible.test(i,j)) {
counter++;
}
}
}
return counter;
}
它通过了所有性能测试,必须有一些更高性能的解决方案,有什么想法吗?
【问题讨论】:
-
你能链接到codewars kata吗?
-
问题链接在哪里?