对于个人项目,我需要创建一个方法,比较两个整数数组并输出它们的相似程度百分比值。阵列可以具有彼此不同的长度。
即。这些可能是我可以得到的数组的例子:
int[] array1 = {21, 154, 25, 180, 2, 159, 25, 25, 181, 25, 3, 181, 25, 180, 2, 160, 4, 179, 21, 2, 159, 17, 54, 21, 158, 25, 180, 21, 25, 180, 21, 4, 100, 46, 79, 25, 180, 21, 25, 180, 21, 4};
int[] array2 = {21, 154, 25, 180, 2, 159, 25, 25, 181, 25, 3, 181, 25, 180, 2, 160, 4, 179, 17, 54, 167, 25, 180, 21, 25, 180, 21, 4, 100, 46, 79, 25, 180, 21, 25, 180, 21, 4, 100, 50, 83, 25, 180, 21, 25, 180};
正如你所看到的那样,第一部分是相同的,但最后一部分只有一些比较。
答案 0 :(得分:0)
我假设您必须计算常见元素的数量,然后对其进行一些处理。
你的问题是严格的算法问题:最简单的解决方案是排序数组(n * log(n))然后迭代它们以获得它们共有多少个元素(可以在一个循环中完成它所以你有n操作)。它给我们O(n * log(n)+ n)什么是(n * log(n))。
但是有更好的方法 - 你可以使用关联数组,你需要更多的内存(对于这个额外的数组),然后检查它们有多少共同点。它给你n用于放入数组和n用于找出它们有多少共同点。所以你有O(n + n)所以它是O(n)。
public class Compare {
public static Integer min(Integer a, Integer b) {
if (a != null && b != null) {
if (a.intValue() > b.intValue())
return b;
else
return a;
} else
// If any of them is null
return 0;
}
public static void how_many_common(int[] arr1, int[] arr2) {
System.out.println("First arr has " + arr1.length);
System.out.println("Second arr has " + arr2.length);
Map<Integer, Integer> arr1_map = new HashMap<>();
Map<Integer, Integer> arr2_map = new HashMap<>();
// Put first arr in Hash map
for (int i : arr1) {
Integer how_many = arr1_map.get(i);
if (how_many != null) {
arr1_map.put(i, how_many + 1);
} else {
arr1_map.put(i, 1);
}
}
// Put second arr in Hash map
for (int i : arr2) {
Integer how_many = arr2_map.get(i);
if (how_many != null) {
arr2_map.put(i, how_many + 1);
} else {
arr2_map.put(i, 1);
}
}
int sumOfCommon = 0;
for (int i : arr1_map.keySet()) {
sumOfCommon += min(arr1_map.get(i), arr2_map.get(i));
}
System.out.println("Arrays have " + sumOfCommon + " numbers in common");
//Rest of likeliness is for you
}
public static void main(String[] args) {
int[] array1 = {21, 154, 25, 180, 2, 159, 25, 25, 181, 25, 3, 181, 25, 180, 2, 160, 4, 179, 21, 2, 159, 17, 54, 21, 158, 25, 180, 21, 25, 180, 21, 4, 100, 46, 79, 25, 180, 21, 25, 180, 21, 4};
int[] array2 = {21, 154, 25, 180, 2, 159, 25, 25, 181, 25, 3, 181, 25, 180, 2, 160, 4, 179, 17, 54, 167, 25, 180, 21, 25, 180, 21, 4, 100, 46, 79, 25, 180, 21, 25, 180, 21, 4, 100, 50, 83, 25, 180, 21, 25, 180};
how_many_common(array1, array2);
int [] array3 = {1,2,3,4};
int [] array4 = {1,2,3,4};
how_many_common(array3, array4);
int [] array5 = {};
int [] array6 = {1,2,3,4};
how_many_common(array5, array6);
int [] array7 = {5};
int [] array8 = {1,2,3,4};
how_many_common(array7, array8);
}
}
完成了第二种方法的工作解决方案。