首页 > 其他分享 >【哈希表】LeetCode 350. 两个数组的交集 II

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

时间:2023-01-07 13:11:07浏览次数:57  
标签:count int II ++ 哈希 350 nums1 nums2

题目链接

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();
    }
}

标签:count,int,II,++,哈希,350,nums1,nums2
From: https://www.cnblogs.com/shixuanliu/p/17032493.html

相关文章