求两个数组的重复数据

public class DoublePointer {

    public static int[] a = new int[]{1, 3, 4, 9};

    public static int[] b = new int[]{0, 3, 4, 4};

    public static void main(String[] args) {
        System.out.println("两个数组重合数据为:" + intersection(a, b));
    }

    public static List<Integer> intersection(int[] a, int[] b) {
        //a 或者 b 有一个为null,则返回null
        if (a == null || b == null) {
            return null;
        }
        //设置最小的位数
        List<Integer> temp = new ArrayList<>();
        //首先排序,从小到大
        Arrays.sort(a);
        Arrays.sort(b);
        for (int i = 0, j = 0; i < a.length && j < b.length; ) {
            if (a[i] == b[j]) {
                temp.add(a[i]);
                i++;
                j++;
            } else if (a[i] > b[j]) {
                j++;
            } else {
                i++;
            }
        }
        return temp;
    }


}

 

posted @ 2021-06-15 16:09  活出自己范儿  Views(344)  Comments(0)    收藏  举报