如何找到三个排序数组的交集并将交集作为数组返回

时间:2019-07-11 12:28:29

标签: java arrays

我想找到三个排序数组的交集,并在一个新数组中返回该交集。我在将相交传递到新数组“结果”时遇到问题。我将数组结果初始化为arr1 [i],它返回的i值为0。请问如何使新数组结果返回交集?请不要被问题冒犯,我已经在堆栈溢出中看到了类似的解决方案,但是我错过了一些东西,感谢您的帮助。 (我的问题是返回数组,这里的解决方案都不是返回数组,它们都在打印交集。我的问题是将交集作为数组返回)谢谢。

public class ThreeSortedArrays {

    public static void main(String[] args) {

        int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int[] arr2 = {3, 5, 8, 13, 27, 99};
        int[] arr3 = {1, 5, 6, 7, 8};

        findInter(arr1, arr2, arr3);
    }

    public static int[] findInter(int[] arr1, int[] arr2, int[] arr3) {
        int i = 0, j = 0, k = 0;
        int[] result = new int[arr1[i]];

        while (i < arr1.length && j < arr2.length && k < arr3.length) {
            if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
                i++;
                j++;
                k++;
            } else if (arr1[i] < arr2[j]) {
                i++;
            } else if (arr2[j] < arr3[k]) {
                j++;
            } else {
                k++;
            }
        }
        for (int x = 0; x < result.length; x++) {
            System.out.println(result[x]);
        }
        return result;
    }
}

0 个答案:

没有答案