【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
- 【leetcode76】Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays&Intersection of Two Arrays II
- [LeetCode] Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 【多线程】java.util.concurrent.Exchanger应用范例与原理浅析
- window平台安装 MongoDB
- 百度面试之第一回合
- HDU 5779 Tower Defence
- The file cannot be validated as the XML definition 异常解决办法
- 【leetcode76】Intersection of Two Arrays II
- 架构漫谈(五):什么是软件
- 2016多校训练Contest4: 1005 Lucky7 hdu5768
- 多线程--线程同步
- 用chrome调试Android程序
- 从头学android_LocationManager的使用
- 工作三周总结
- Zookeeper报错Will not attempt to authenticate using SASL解决办法
- Python爬虫入门四之Cookie的使用