比较两个数组的共同项目和 return 另一个数组与共同项目

compare two arrays for common Items and return another array with the common items

所以问题是我有两个数组,必须检查它们是否有常见的 items.Usual 东西,非常 easy.But 对我来说棘手的事情是我必须 return 另一个数组到目前为止,我的代码是 common.I 中的元素不能在 advance.This 中使用任何 Collections.Thanks!

public class checkArrayItems {
    static int[] array1 = { 4, 5, 6, 7, 8 };
    static int[] array2 = { 1, 2, 3, 4, 5 };

    public static void main(String[] args) {
        checkArrayItems obj = new checkArrayItems();
        System.out.println(obj.checkArr(array1, array2));

    }

    int[] checkArr(int[] arr1, int[] arr2) {
        int[] arr = new int[array1.length];
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) {
                    arr[i] = arr1[i];
                }

            }
        }
        return arr;

    }

}

我懒得敲代码了,但是算法在这里。 1.对两个数组进行排序 2. 遍历数组比较项并增加索引。

希望对您有所帮助。

在两个for循环之前声明一个索引

int index = 0;

这将保存 arr 数组的当前位置。那么:

arr[index++] = arr1[i];

而且,由于您使用 arr1.lenght 初始化 arr,您的数组将在非冲突结束时填充为 0。

您可以使用 arr[i] = Integer.MIN_VALUE; 为新数组 arr 中的元素使用 MIN 或 MAX 默认虚拟值。通过这种方式,您将能够区分真实值和虚拟值。如下所示:

int[] checkArr(int[] arr1, int[] arr2) {
        int[] arr = new int[array1.length];
        for (int i = 0; i < arr1.length; i++) {
            arr[i] = Integer.MIN_VALUE;
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) {
                    arr[i] = arr1[i];
                }

            }
        }
        return arr;

    }

输出

[4, 5, -2147483648, -2147483648, -2147483648]

编辑

结论 当您遍历 arr 时,除 -2147483648 之外的所有值都是常见的。

编辑 2

打印下面评论中提到的常用值:

public static void main(String[] args) {
checkArrayItems obj = new checkArrayItems();
int[] arr = obj.checkArr(array1, array2);
        System.out.println("Common values are : ");
        for (int x : arr) {
            if (x != Integer.MIN_VALUE) {
                System.out.print(x+"\t");
            }
        }
}

建议: 遵循 class 的命名约定,即将 checkArrayItems 改为 CheckArrayItems

如果有人想知道@user3438137 提到的 "chasing" 算法是怎样的:

int[] sorted1 = Arrays.copyOf(array1, array1.length);
Arrays.sort(sorted1);
int[] sorted2 = Arrays.copyOf(array2, array2.length);
Arrays.sort(sorted2);
int[] common = new int[Math.min(sorted1.length, sorted2.length)];
int numCommonElements = 0, firstIndex = 0; secondIndex = 0;
while (firstIndex < sorted1.length && secondIndex < sorted2.length) {
    if (sorted1[firstIndex] < sorted2[secondIndex]) firstIndex++;
    else if (sorted1[firstIndex] == sorted2[secondIndex]) {
        common[numCommonElements] = sorted1[firstIndex];
        numCommonElements++;
        firstIndex++;
        secondIndex++;
    }
    else secondIndex++;
}
// optionally trim the commonElements array to numCommonElements size