我有一個數組,我的目標是找出有多少間隔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
目前我有什麼是基本的,每個數組中元素貫穿,檢查所有其他元素與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個循環。 –
但仍然 - 你的第一個例子只有16和27.另一對是什麼? –
是的我想我應該將它理解爲「多少個NUMBERS分享11的差異」。 16和27是2個數字,所以2 – bZhang