Intersection of Two Arrays

题目
Given two arrays, write a function to compute their intersection.

答案

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set s1 = new HashSet<>();
        Set s2 = new HashSet<>();
        
        for(int num : nums1) {
            s1.add(num);
        }
        
        for(int num : nums2) {
            if(s1.contains(num)) {
                s2.add(num);
            }
        }
        int size = s2.size(), i = 0;
        int[] ret = new int[size];
        for(int num : s2)
            ret[i++] = num;
        return ret;
    }
}

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