Simple Java solution using "Single HashSet". O(n)


  • 0
    M

    We can solve it using one hash set, but we need to remove elements as we add them to the result array.

    public class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            Set<Integer> set = new HashSet<>();
            for( int i = 0; i < nums2.length; i++ )
            {
                set.add(nums2[i]);
            }
            int[] result = new int[set.size()];
            int i = -1, j = 0;
            while( i < nums1.length - 1 )
            {
                if( set.contains(nums1[++i]) )
                {
                    result[j++] = nums1[i];
                    set.remove(nums1[i]);
                }
            }
            return Arrays.copyOf(result, j);
        }
    }
    

Log in to reply
 

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