congr / world

2 stars 1 forks source link

LeetCode : 349. Intersection of Two Arrays #437

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/intersection-of-two-arrays/

image

congr commented 5 years ago
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet();
        Set<Integer> intersect = new HashSet();

        for (int n : nums1) set.add(n);
        for (int n : nums2) 
            if (set.contains(n)) intersect.add(n);

        int i = 0;
        int[] res = new int[intersect.size()];
        for (int n : intersect) res[i++] = n;
        return res;
    }
}