[LeetCode] Intersection of Two Arrays
2016-05-19 10:43
447 查看
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 =
Note:
Each element in the result must be unique.
The result can be in any order.
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.
解题思路
首先用map存储数组1里出现的元素,然后检查这些元素是否也在数组2中存在,如果存在则将该元素添加到返回的数组中。实现代码
// Runtime: 8 ms public class Solution { public int[] intersection(int[] nums1, int[] nums2) { Map<Integer, Integer> map = new HashMap<>(); for (int num : nums1) { map.put(num, 1); } int len = 0; for (int num : nums2) { if (map.containsKey(num) && map.get(num) == 1) { map.put(num, 2); ++len; } } int[] nums = new int[len]; int i = 0; for (Map.Entry<Integer, Integer> entry : map.entrySet()) { if (entry.getValue() == 2) { nums[i++] = entry.getKey(); } } return nums; } }
相关文章推荐
- SoftReference 为什么被 Android “放弃”
- 拼音库
- uploadify的使用
- Android开发效率—Eclipse快捷键
- ASP.NET MVC验证 - 自定义验证规则、验证2个属性值不等【待验证】
- Invalid action class configuration that references an unknown class问题原因之s:select
- mysql出现innodb缺失错误 #1286
- 第三十七课 Spark之Task执行原理及结果
- C# 开发者最经常犯的 8 个错误
- 增加几个entity framework 的函数 (记录备忘)[转]
- 浅谈Java中的锁
- 硬盘安装CentOS有个关键点
- android-async-http使用总结
- iOS开发——keychain的使用
- oscache 页面缓存的轻松实现
- iOS性别枚举
- Java Map集合按照key和value排序之法
- Java发送电子邮件的完整代码,可发送附件
- 多级神经网络结构表达文档语义性能更好吗
- 12 种编程语言的起源故事