哈希表-两个数的交集

代码随想录-刷题笔记

349. 两个数组的交集 - 力扣(LeetCode)

内容:

集合的使用 , 重复的数剔除掉,剩下的即为交集,最后加入数组即可。

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set result = new HashSet<>();
        Map map = new HashMap<>();
        for(int i : nums1) {
            map.put(i,map.getOrDefault(i, 0) + 1);
        }
        for(int j : nums2) {
            if(map.getOrDefault(j, 0) != 0) {
                result.add(j);
            }
        }
        return result.stream().mapToInt(Integer::intValue).toArray();
    }
}

总结:

集合入门.

你可能感兴趣的:(散列表,算法,数据结构)