leetcode[Intersection of Two Arrays II]
来源:互联网 发布:linux内核缓冲区 编辑:程序博客网 时间:2024/06/17 20:53
[Intersection of Two Arrays]的一些解法也可以拿过来用,只不过存储结果一个用set一个用list而已
解法一:
public class Solution { public int[] intersect(int[] nums1, int[] nums2) { LinkedList<Integer> list = new LinkedList<>(); for(int i = 0; i < nums1.length; i++){ list.add(nums1[i]); } LinkedList<Integer> temp = new LinkedList<>(); for(int i = 0; i < nums2.length; i++){ if(list.contains(nums2[i])){ temp.add(nums2[i]); //list.remove(nums2[i]);//因为要保留重复元素,原来nums1对应的list要删除这个元素 list.remove(new Integer(nums2[i]));//这里有个重载,若remove参数是int,代表下标,integer才代表对象 } } int[] res = new int[temp.size()]; for(int i = 0; i < res.length; i++){ res[i] = temp.get(i); } return res; }}
解法二:
public class Solution { public int[] intersect(int[] nums1, int[] nums2) { //题目中的follow-up提到考虑内存问题,那么就将nums1的重复元素计数,用Map来存 HashMap<Integer, Integer> map = new HashMap<>();//将nums1存到map中去 for(int i = 0; i < nums1.length; i++){ if(map.containsKey(nums1[i])){ map.put(nums1[i], map.get(nums1[i]) + 1); //System.out.println("" + nums1[i] + " : " + (map.get(nums1[i]))); } else{ map.put(nums1[i], 1); } } LinkedList<Integer> temp = new LinkedList<>(); //开始求交集 for(int i = 0; i < nums2.length; i++){ if(map.containsKey(nums2[i])){ temp.add(nums2[i]); if(map.get(nums2[i]) == 1){//当这个元素在map中只有一个时,移除map中的一个键值对(因为求交集移了一个就只剩0个了) map.remove(nums2[i]); } else{ map.put(nums2[i], map.get(nums2[i]) - 1);//计数减一 } } } int[] res = new int[temp.size()]; for(int i = 0; i < res.length; i++){ res[i] = temp.get(i); } return res; }}
阅读全文
0 0
- [LeetCode] Intersection of Two Arrays II
- LeetCode Intersection of Two Arrays II
- LeetCode 350. Intersection of Two Arrays II
- LeetCode:Intersection of Two Arrays II
- leetcode.350. Intersection of Two Arrays II
- LeetCode 350:Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- leetcode Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- [python][leetcode]Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- 【leetcode】Intersection of Two Arrays II
- 【leetcode】350. Intersection of Two Arrays II
- leetcode之Intersection of Two Arrays II
- [Leetcode] 350. Intersection of Two Arrays II
- CUDA(三) 三种memory的活用
- retrofit 注解学习
- Git命令导图
- 导入AndroidStudio项目时,一开始就卡在了Building gradle project info
- 几个简单实用的CMD小命令
- leetcode[Intersection of Two Arrays II]
- 【二叉树】字符串打印树结构/路径【606. Construct String from Binary Tree】【257. Binary Tree Paths】【102. Binary Tree Le
- mybatis知识点总结之数据源和连接池
- 日志系列--计量日志处理方案
- <c:forEach> 合计金额
- Mac下使用Aria2下载教程----迅雷和百度盘终极解决方案
- elasticsearch聚合案例--分组、求最大值再求最大值的均值
- C# using语句的使用
- ios-正则表达式使用的三种方法和正则表达式