可以使用两个指针分别指向两个数组的起始位置,然后按照有序数组的特点逐个比较元素,将相同的元素存放到新数组中。

具体实现如下:

import java.util.ArrayList;
import java.util.List;

public class IntersectionOfTwoArrays {
    public static void main(String[] args) {
        int[] a = {0, 1, 2, 3, 4};
        int[] b = {1, 3, 5, 7, 9};
        int[] intersection = findIntersection(a, b);
        for (int num : intersection) {
            System.out.print(num + " ");
        }
    }

    public static int[] findIntersection(int[] a, int[] b) {
        List<Integer> intersectionList = new ArrayList<>();
        int i = 0, j = 0;

        while (i < a.length && j < b.length) {
            if (a[i] < b[j]) {
                i++;
            } else if (a[i] > b[j]) {
                j++;
            } else {
                intersectionList.add(a[i]);
                i++;
                j++;
            }
        }

        int[] intersection = new int[intersectionList.size()];
        for (int k = 0; k < intersectionList.size(); k++) {
            intersection[k] = intersectionList.get(k);
        }

        return intersection;
    }
}

输出结果为:1

如何计算两个有序整型数组没有重复元素的交集?例如 a=01234;b=13579; 交集为13。 获取两个数组中的相同元素并存放到新数组中java实现

原文地址: http://www.cveoy.top/t/topic/inLC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录