[LeetCode] 350. 两个数组的交集 II

时间:2020-07-22 11:31:19   收藏:0   阅读:64

一开始的想法是:用一个map来存储长度较长的数组中的所有数字,再与较短的数组中的数字比较,若出现在较长数组中,则map中的数量减一,最后用原始map与比较结束后的map比较,得到重复的数字有哪些。

答案的解法:

技术图片

用一个数组来存储比较的结果:

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        // 将长度短的数组换到前面。
        if (nums1.length > nums2.length) {
            return intersect(nums2, nums1);
        }
        // 创建 HashMap 记录 nums1 中每个元素出现的次数。
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int num : nums1) {
            int count = map.getOrDefault(num, 0) + 1;
            map.put(num, count);
        }
        int[] ans = new int[nums1.length];
        int index = 0;
        // 遍历数组 nums2 中元素,在 HashMap 中个数大于 0 则记录。
        for (int num : nums2) {
            int count = map.getOrDefault(num, 0);
            if (count > 0) {
                ans[index++] = num;
                count--;
                if (count > 0) {
                    map.put(num, count);
                } else {
                    map.remove(num);
                }
            }
        }
        // 遍历完成返回重复元素长度的结果数组。
        return Arrays.copyOfRange(ans, 0, index);
    }
}

作者:iceblood
链接:https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/solution/350ti-liang-ge-shu-zu-de-jiao-ji-ii-by-iceblood/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

技术图片

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!