[英]How to check max number of elements that are spaced evenly?
我有一个数组,我的目标是找出以11的倍数分隔的数组。数组未排序。
Such as [27, 16, 52, 84], this would return 2
[1, 55, 66, 33] should return 3.
[99, 8, 52, 32] should return 0
目前,我所需要的基本上是遍历数组中的for-each元素,并乘以11来检查所有其他元素。但是,这使我处于O(n²)运行时,无论如何我都可以优化它?
static int eval(int [] a) {
int i, j, k, counter = 0;
for (i = 0; i < a.length; i++) {
for (j = 0; j < a.length; j++) {
if (i != j) {
for (k = -9; k < 10; k++) {
if (a[i] == a[j] + k*11) {
counter++;
break;
}
}
}
}
}
//if found nothing, will return 0, if found 1 matching,
//it should be 2 numbers that share this 11-difference.
return counter : counter == 0? 0: counter + 1;
}
谢谢!
您将需要2个循环来完成此操作。 计算每个元素之间的差,如果该数字是11的倍数,则增加计数器。 返回一半的计数器,就好像您在两个元素之间命中了11的倍数一样,您最终将在循环的后面再次命中相同的两个元素:
static int eval(int [] a) {
int counter = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
if (i != j && Math.abs(a[i] - a[j]) % 11 == 0) {
counter++;
}
}
}
return counter / 2;
}
例如[11, 22, 34, 45]
尚不清楚输出应该是什么。 我将问题解释为要求输入的最大子集的大小,其中子集元素之间的所有差异都是11的倍数,而大小1子集不计算在内。
具有相同残差mod 11的所有输入都以11的倍数间隔,因此我们只需要计算输入中有多少个int分别具有i % 11
可能值。 这需要时间成线性的输入大小。
static int eval(int[] a) {
int[] inputsPerResidue = new int[11];
for (int i : a) {
inputsPerResidue[i % 11]++;
}
int maxGroupSize = 0;
for (int groupSize : inputsPerResidue) {
if (groupSize > 1 && groupSize > maxGroupSize) {
maxGroupSize = groupSize;
}
}
return maxGroupSize;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.