349. Intersection of Two Arrays
来源:互联网 发布:朴素贝叶斯算法matlab 编辑:程序博客网 时间:2024/06/06 01:58
349. Intersection of Two Arrays
DescriptionHintsSubmissionsDiscussSolution
DiscussPick One
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.
Seen this question in a real interview before?
题意
求两个数组得并集
算法思路
把第一数组放到hashset中,然后遍历第二数组,如果hash中有第二组中得元素,加入结果,从hash中移除
代码
package easy;import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;public class IntersectionofTwoArrays {public int[] intersection(int[] nums1, int[] nums2) {if(nums1 == null || nums2== null){return null;}if(nums1.length == 0 || nums2.length == 0){return new int[0];}Set<Integer> set = new HashSet<Integer>();for(int i=0; i<nums1.length; i++){set.add(nums1[i]);}List<Integer> result = new ArrayList<Integer>();for(int i=0; i<nums2.length; i++){if(set.contains(nums2[i])){result.add(nums2[i]);set.remove(nums2[i]);}}int[]a=new int[result.size()]; for(int i=0;i<result.size();i++){ a[i]=(int)result.get(i); } return a; }}
阅读全文
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
- 正确理解ThreadLocal
- poj1745(后缀数组+二分)
- bzoj1927 [Sdoi2010]星际竞速
- Qt中验证器的使用
- 交叉编译iptables1.4.12的问题
- 349. Intersection of Two Arrays
- 斐波那契数列(NOIP1997)
- javaSE_IO流
- SimpleAudioEngine使用的一些感悟
- Codeforces 825G Tree Queries(DFS)
- 初学java--抽象的认识
- Because we are OIer
- firebird优化笔记
- CSS3 选择器、颜色与度量单位、文本、边框、背景