我有N
整數數組爲every index i
其中N<= 10^6
我一定要找到我這樣A[j]%A[i]==0 0<j<i
查找最近Divisable在
例
3 4 2 6 7 3
Nearest Neighbor array
-1 -1 1 -1 -1 3
As for last element i.e 3 6%3==0 and index of 6 is 3 so ans is 3
similar for 2 nearest neighbor is 4
蠻力最接近的左鄰的數組方法
int[] Neg = new int[n];
Arrays.fill(Neg,-1);
for(int i=1;i<n;i++)
for(int j=i-1;j>=0;j--)
if(A[j]%A[i]==0){
Neg[i]=j;
break;
}
This O(n^2) approach and will fail
我怎麼能想出更好的辦法可能是O(nlogn)
數組元素的最大可能值是多少? – dreamzor
你的「整數數組」中的值有沒有限制?或者整數範圍爲'-2^31 .. 2^31 - 1' – Aivean
@Aivean值範圍在1到10^6 – Sunny