O(N) simple solution in Java using HashSets


  • 2
    V
    public int[] intersection(int[] nums1, int[] nums2) {
            HashSet<Integer> set = new HashSet<>();
            HashSet<Integer> inter = new HashSet<>();
            for(int i = 0 ; i < nums1.length ; i++)
                set.add(nums1[i]);
            for(int i = 0 ; i < nums2.length ; i++){
                if(set.contains(nums2[i]))
                    inter.add(nums2[i]); // only add unique elements common to both
            }
            int[] result = new int[inter.size()];
            int count = 0;
            for(Integer in : inter)
                result[count++] = in;
                
            return result;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.