【leetcode76】Intersection of Two Arrays II

来源:互联网 发布:centos wget 命令 编辑:程序博客网 时间:2024/05/21 17:46

题目描述:

给定两个数组求他们的公共部分,输出形式是数组,相同的元素累计计数

例如:

nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

原文描述:

Given two arrays, write a function to compute their intersection.

Example:

Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note:

Each element in the result must be unique.
The result can be in any order.

思路:

  • 使用HashMap(Integer,Integer)的数据结构,首先遍历Array1
  • 遍历Array2,如果Array1包含,而且get(key)的value减一还大于0,就继续

代码:

 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();        HashMap<Integer, Integer> resultMap = new HashMap<Integer, Integer>();        ArrayList<Integer> list = new ArrayList<Integer>();        for (int i = 0; i < nums1.length; i++) {            if (!map.containsKey(nums1[i])) {                map.put(nums1[i], 1);            } else {                map.put(nums1[i], map.get(nums1[i])  + 1);            }        }        for (int j = 0; j < nums2.length; j++) {            if (map.containsKey(nums2[j]) && map.get(nums2[j]) > 0) {                map.put(nums2[j], map.get(nums2[j]) - 1);                if (!resultMap.containsKey(nums2[j])) {                    resultMap.put(nums2[j], 1);                } else {                    resultMap.put(nums2[j], resultMap.get(nums2[j]) + 1);                }            }        }        int sum = 0;        for (Integer e : resultMap.keySet()) {            int count = resultMap.get(e);            sum += count;            for (int i = 0; i < count; i++) {                list.add(e);            }        }        int[] result = new int[sum];        for (int i = 0; i < sum; i++) {            result[i] = (int) list.get(i);        }        return result;

更多leetcode题目,请看我的leetcode专栏。链接如下:

leetcode专栏

我的微信二维码如下,欢迎交流讨论

这里写图片描述

欢迎关注《IT面试题汇总》微信订阅号。每天推送经典面试题和面试心得技巧,都是干货!

微信订阅号二维码如下:

这里写图片描述

1 0
原创粉丝点击