如何创建一个比较 2 个整数数组并获得它们相似程度的百分比的方法



对于个人项目,我需要创建一个方法,比较两个整数数组并输出它们相似程度的百分比值。数组之间的长度可以不同。

即这些可能是我可以得到的数组示例:

    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};

如您所见,第一部分是相同的,但最后一部分只有一些比较。

我假设你必须计算公共元素的数量,然后做一些事情。

你的问题是严格的算法问题:最简单的解决方案是对数组(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);
}
}

它完成了第二种方法的工作解决方案。

相关内容

最新更新