Java Solution using HashSet


  • 0
    C

    1.) Add Elements from array 1 to HashSet
    2.) Iterate over array 2 and check if element is in HashSet
    3.) If HashSet contains the element, then add the element to list which stores the result and remove the element from HashSet.
    4.) Convert List to Array, return this Array.

    public class Solution {
        public int[] intersect(int[] nums1, int[] nums2) {
            List<Integer> hs =new ArrayList<Integer>();
            List<Integer> l =new ArrayList<Integer>();
            for(int i:nums1){
                hs.add(i);
            }
            for(int j:nums2){
                if(hs.contains(j)){
                    l.add(j);
                    hs.remove((Integer)j);
                }
            }
            int[] a=new int[l.size()];
            int count=0;
            for(int k:l){
                a[count++]=k;
            }
            return a;
        }
    }
    

Log in to reply
 

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