349. Intersection of Two Arrays
来源:互联网 发布:三菱plc脉冲输出编程 编辑:程序博客网 时间:2024/04/28 00:13
Given two arrays, write a function to compute their intersection.
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.
Subscribe to see which companies asked this question
解题思路: 给出A/B数组,求出B数组的数字在A数组数字出现的次数。做法是将A数组的数字概率分布放到hashmap中,然后遍历B数组,匹配到有这个数字,则将结果放入到set中,最后将set转化成数组,返回结果。
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); HashSet<Integer> set = new HashSet<Integer>(); for(int i = 0 ; i < nums1.length; ++i) { if(map.containsKey(nums1[i])) { int value = map.get(nums1[i]); value++; map.put(nums1[i], value); }else { map.put(nums1[i], 1); } } for(int i = 0; i < nums2.length; ++i) { if(map.containsKey(nums2[i])) { set.add(nums2[i]); } } int[] result = new int[set.size()]; int i=0; for(int n:set) { result[i] = n; i++; } return result; }}
0 0
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays[][
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 知识点:树状数组讲解
- 编程思想(1)
- 3.2决策树理论2--python深度机器学习
- Elasticsearch的使用场景深入详解
- C\C++中头文件string与string.h的区别
- 349. Intersection of Two Arrays
- 大数据Spark“蘑菇云”行动-第11课:Scala面向接口彻底实战和Spark源码鉴赏
- YII 中session和cookie的用法
- 【#英语造句1#】
- H-Index II
- Caffe学习笔记
- 最优雅,高效的javascript字符串拼接
- 事件分发与拦截
- xampp中Apache启动时443端口被占用