leetcode(83).350. Intersection of Two Arrays II
来源:互联网 发布:澳门娱乐网络博客 编辑:程序博客网 时间:2024/05/29 04:24
题意:
返回给定两个数组的交集(所有匹配的元素,包括多次匹配的的)
初步分析:
还是用hashmap,只要将map的value理解为第一个数组中的个数,第二个数组每匹配掉一个,都将value减1,当value等于0的时候,就相当于已经匹配完了。
我们是没有办法时候通过value值判断它到底匹配过没有,匹配过几次的,所以只能当场添加,所以使用动态数组。
public class Solution { public int[] intersect(int[] nums1, int[] nums2) { HashMap<Integer, Integer> hm = new HashMap<>(); ArrayList<Integer> al = new ArrayList<>(); int count = 0; for(int i=0; i<nums1.length; i++) { if(!hm.containsKey(nums1[i])) hm.put(nums1[i],1); else hm.put(nums1[i],hm.get(nums1[i])+1); } for(int i=0; i<nums2.length; i++) { if(hm.containsKey(nums2[i]) && hm.get(nums2[i])>0) { hm.put(nums2[i],hm.get(nums2[i])-1); al.add(nums2[i]); } } int[] ret = new int[al.size()]; for(int i=0; i<ret.length; i++) ret[i] = al.get(i); return ret; }}
0 0
- 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 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】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-350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- [leetcode]350. Intersection of Two Arrays II
- Blue Jeans
- Ultra-QuickSort
- 阻塞队列BlockingQueue
- LeetCode 290. Word Pattern
- 高精度加法
- leetcode(83).350. Intersection of Two Arrays II
- NFS 网络文件系统 安装配置
- poj2942 Knights of the Round Table
- Android热修复原理(HotFix)初涉
- hdu 2612 Find a way
- 递归
- 获取网页内容---"User-Agent"
- SElinux
- Spark 调度架构原理深度解析