假设有n个数组,每个数组中都有不同的Integer
值。如何使用Java从彼此的m个数内找到整数?
例如:
数组1:22, 23, 210, 221, 231, 236, 237, 251, 254, 278, 300, 316, 320
阵列2:230
阵列3:365, 366, 367, 373, 410, 413, 415, 417, 419
我希望有一个算法来分析这些给定的数组,其值为m=1
,并输出对231:Array1, 230:Array2
。什么是最好的方法?
最佳答案
有一种方法:
一。定义数组:
int [] arr1 = {22, 23, 210, 221, 231, 236, 237, 251, 254, 278, 300, 316, 320};
int [] arr2 = {230};
int [] arr3 = {365, 366, 367, 373, 410, 413, 415, 417, 419};
2.将所有数组放入集合:
List<Set<Integer>> sets = new ArrayList<>();
addSets(sets, arr1, arr2, arr3);
// Time: O(n * k) where n=number of arrays and k=size of largest array
private static void addSets(List<Set<Integer>> sets, int [] ... arrs)
{
for (int [] arr : arrs)
{
Set<Integer> s = new HashSet<>();
for (int i : arr)
{
s.add(i);
}
sets.add(s);
}
}
三。定义m:
int m = 1;
四查找群集:
List<String> pairs = findClusters(sets, m);
// Time: O(n^2 * k) where n=number of arrays and k=size of largest array
private static List<String> findClusters(List<Set<Integer>> sets, int m)
{
// holds the pairs
List<String> pairs = new ArrayList<>();
for (int i = 0; i < sets.size() - 1; i++)
{
Set<Integer> primary = sets.get(i);
for (int j = i + 1; j < sets.size(); j++)
{
Set<Integer> secondary = sets.get(j);
for (int p : primary)
{
if (secondary.contains(p - m))
{
pairs.add(p + ", " + (p-m));
}
if (secondary.contains(p + m))
{
pairs.add(p + ", " + (p+m));
}
}
}
}
return pairs;
}
5个打印对:
for (String pair : pairs)
System.out.println(pair);
总运行时间:
O((k * n) + (k * n^2))