349. Intersection of Two Arrays

public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        HashSet set=new HashSet<>();
        ArrayList arr=new ArrayList<>();
        for(int num:nums1) set.add(num);
        for(int num:nums2){
            if(set.contains(num)){
                set.remove(num);
                arr.add(num);
            }
        }
        int k=0;
        int[] res=new int[arr.size()];
        for(Integer num: arr){
            res[k++]=num;
        }
        return res;
    }
}

你可能感兴趣的:(349. Intersection of Two Arrays)