【哈希表】LeetCode 350. 两个数组的交集 II

题目链接

350. 两个数组的交集 II

思路

建立两个哈希表分别统计 nums1nums2 中每个数字出现的个数,然后同时遍历两个哈希表,对两个对位元素取其最小值 count,将 count 数量的数字放入结果数组中。

代码

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        int[] map1 = new int[1001];
        int[] map2 = new int[1001];

        for(int i = 0; i < nums1.length; i++){
            map1[nums1[i]]++;
        }
        for(int i = 0; i < nums2.length; i++){
            map2[nums2[i]]++;
        }

        ArrayList<Integer> res = new ArrayList<>();
        for(int i = 0; i < 1001; i++){
            int count = Math.min(map1[i], map2[i]);
            System.out.println("i = " + i + ", count = " + count);
            for(int j = 0; j < count; j++){
                res.add(i);
            }
        }

        return res.stream().mapToInt(i -> i).toArray();
    }
}
posted @ 2023-01-07 13:04  Frodo1124  阅读(23)  评论(0编辑  收藏  举报