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;    }}


原创粉丝点击