349. 两个数组的交集

161 阅读1分钟

题目描述

方法1

两个hashset

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();
        for (int x : nums1) {
            set1.add(x);
        }
        for (int x : nums2) {
            set2.add(x);
        }
        int size = nums1.length > nums2.length ? nums1.length : nums2.length;
        int[] res = new int[size];// 按大的长度建res
        int i = 0;
        for (int x : set1) {
            if (set2.contains(x)) {
                res[i] = x;
                i++;
            }
        }
        return Arrays.copyOf(res, i);// 去掉后面的0, 从0到i-1
    }
}

方法2

  • 先排序
  • 然后双指针比对

IMG_A5EFAAFD3A7B-1.jpeg

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        // 先排序
        Arrays.sort(nums1);
        Arrays.sort(nums2);

        int i = 0, j = 0, k = 0;
        int size = nums1.length > nums2.length ? nums1.length : nums2.length;
        int[] res = new int[size];// 按大的长度建res
        // 放心用&&
        while (i < nums1.length && j < nums2.length) {
            // 去重复
            if ((i == 0 || nums1[i] != nums1[i - 1] ) && nums1[i] == nums2[j]) {
                res[k] = nums1[i];
                i++;
                j++;
                k++;
            } else if (nums1[i] < nums2[j]){
                i++;
            } else {
                j++;
            }
        }
        return Arrays.copyOf(res, k);
    }
}

方法3

  • 先把一个数组放到HashMap<元素,1>中,相当于去一次重。
  • 再遍历另一个数组,如果能在HashMap中找到,说明是重叠元素,加到res中。注意这一步也需要去重,往res添加过的重复元素要吗map中的value改一下。
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int x : nums1) {
            map.put(x, 1);//去重
        }
        List<Integer> list = new ArrayList<>();
        for (int y : nums2) {
            if (map.containsKey(y) && map.get(y) == 1) {//防止重复添加4或9 [4,9,5], [9,4,9,8,4]
                list.add(y);
                map.put(y, 2);
            }
        }
        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }
        return res;
    }
}