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