548.Intersection of Two Arrays II-两数组的交 II(容易题)
来源:互联网 发布:量化交易 不会编程 编辑:程序博客网 时间:2024/05/17 04:08
两数组的交 II
题目
计算两个数组的交
注意事项
每个元素出现次数得和在数组里一样
答案可以以任意顺序给出样例
nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].
题解
先对nums1遍历并将nums1[i]和nums1[i]出现次数存入HashMap,再对nums2进行遍历,如果任意nums2[i]在HashMap中存在且Value大于0则标记为相交数,并将Value计数-1。
public class Solution { /** * @param nums1 an integer array * @param nums2 an integer array * @return an integer array */ public int[] intersection(int[] nums1, int[] nums2) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); List<Integer> results = new ArrayList<Integer>(); for(int i = 0; i < nums1.length; ++i) { map.put(nums1[i], map.containsKey(nums1[i])?(map.get(nums1[i]) + 1):1); } for (int i = 0; i < nums2.length; ++i) { if (map.containsKey(nums2[i]) && map.get(nums2[i]) > 0) { results.add(nums2[i]); map.put(nums2[i], map.get(nums2[i]) - 1); } } int result[] = new int[results.size()]; for(int i = 0; i < results.size(); ++i) { result[i] = results.get(i); } return result; }}
Last Update 2016.9.18
0 0
- 548.Intersection of Two Arrays II-两数组的交 II(容易题)
- Intersection of Two Arrays II 两数组的交
- 547.Intersection of Two Arrays-两数组的交(容易题)
- Intersection of Two Arrays II(两数组的交叉元素II)
- Intersection of Two Arrays 两数组的交
- LeetCode 350. 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
- [Leetcode] Word Break II
- Leetcode 400. Nth Digit 第n个数字 解题报告
- Mac设置Root密码
- 数组的延伸(浅复制、深复制)
- 8张图理解Java
- 548.Intersection of Two Arrays II-两数组的交 II(容易题)
- bzoj 4174 tty的求助 数论 莫比乌斯反演
- SSH无密码登录配置小结
- struct和typedef struct
- openfire插件编译异常
- Android中Excutor线程池的简单使用
- AngularJs必填、比较、格式验证
- jquery表单验证
- 深度学习优化方法