leetcode 349. Intersection of Two Arrays-[Java]

来源:互联网 发布:windows phone 10微信 编辑:程序博客网 时间:2024/05/22 15:47

原题链接:Intersection of Two Arrays


思路:利用set去除重复,查找两个集合中都有的元素添加进结果集;


public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {         /*            Time complexity:O(m*n)            Space Complexity:O(m+n)        */        if(nums1.length==0 || nums2.length==0)return new int[0];        HashSet<Integer> iset1=new HashSet<>();        HashSet<Integer> iset2=new HashSet<>();        for(int i:nums1)iset1.add(i);        for(int i:nums2)iset2.add(i);        ArrayList<Integer>res=new ArrayList<>();        for(int i:iset1)if(iset2.contains(i))res.add(i);        int[] ret=new int[res.size()];        for(int i=0;i<ret.length;i++)ret[i]=res.get(i);        return ret;    }}


原创粉丝点击