[Leetcode] 350. Intersection of Two Arrays II
来源:互联网 发布:sql server身份验证sa 编辑:程序博客网 时间:2024/06/05 15:14
题目:
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.The result can be in any order.
思路:
把nums1中的元素,放到一个map中key为nums1中的值,values是对应nums1中该值出现的次数。
把nums2中的元素,放到另一个map中key为nums2中的值,values是对应nums2中该值出现的次数。
使用一个list存储结果(原因是不知道结果的大小,可以任意添加元素)
依次遍历存储nums1中元素的map的key值获取对应key值的values。与存储map2中对应的key的values对比。选取values值小的元素n,向list中添加n此key值。
具体代码如下:
public class Solution { public int[] intersect(int[] nums1, int[] nums2) { int len1 = nums1.length; int len2 = nums2.length; if(len1 == 0 || len2 == 0){ return new int[0]; } Map<Integer,Integer> map1 = new HashMap(); Map<Integer,Integer> map2 = new HashMap(); for(int i : nums1){ map1.put(i, map1.getOrDefault(i, 0)+1); }// System.out.println("map1:" + map1.toString()); for(int i : nums2){ map2.put(i, map2.getOrDefault(i, 0)+1); }// System.out.println("map2:" + map2.toString()); List<Integer> list = new ArrayList(); for(int j : map1.keySet()){ if(map2.containsKey(j)){ int l = map1.get(j)>map2.get(j)?map2.get(j):map1.get(j); for(int ll = 0; ll < l; ll++){ list.add(j); } } } int resultLen = list.size(); int[] result = new int[resultLen]; int n = 0; for(int jj: list){ result[n] = jj; n++; } return result; }}
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
- 常用的java工具类
- UIViewController的完整生命周期
- C#实现天气预报
- 10.6 C++标准库的异常类层次结构
- 转载------常用的几种编码方式
- [Leetcode] 350. Intersection of Two Arrays II
- 基于Eclipse Maven的Spring4/Spring-MVC/Hibernate4整合之一 : Maven的pom.xml环境配置及注意方面
- 11.1 标准模板库简介
- 数据结构与算法
- 一招制胜---详解分布式系统里session同步
- 11.2 迭代子类
- Java内存管理和内存区域
- 不用缩进的python
- 11.3 顺序容器类