求两个数组的重复数据

时间:2021-06-15 18:46:19   收藏:0   阅读:0
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;
    }


}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!