leetcode#350 两个数组的交集 II

2020-07-16  本文已影响0人  leeehao

题目

给定两个数组,编写一个函数来计算它们的交集。

输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2,2]
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[4,9]
输入:nums1 = [4,4,9,5], nums2 = [9,4,9,8,4]
输出:[4,4,9]

说明:

进阶:

审题

提取出交集并包含重复项。做好一道题首先需要西西理解题目,本题细节较多故将示例贴至上方。
我们首先考虑使用 hash 来判断某个值是否存在,

  1. 将其中一个数组 Hash 并且将重复的次数保存;
  2. 遍历另一个数组查询 hash 集合中是否存在当前值;
  3. 如果存在将此 hash 对应的计次值减一,需注意判断计次为 0 的情;

第一次

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1 == null || nums2 == null) return new int[0];

        Map<Integer, Integer> map = new HashMap<>();
        for (int i : nums1) {
            int count = map.getOrDefault(i, 0);
            map.put(i, ++count);
        }

        List<Integer> result = new ArrayList<>();
        for (int i : nums2) {
            Integer count = map.get(i);
            if (count != null && count > 0) {
                result.add(i);
                map.put(i, count - 1);
            }
        }

        return toInt(result);
    }
    public int[] toInt(List<Integer> set) {
        int[] a = new int[set.size()];
        int i = 0;
        for (Integer val : set) a[i++] = val;
        return a;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读