Java solution using hashsets


  • 0
    M

    class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
    HashSet<Integer> hs = new HashSet<>();
    HashSet<Integer> hs1 = new HashSet<>();

        for (int i = 0; i < nums1.length; i++) 
        hs.add(nums1[i]);
          for (int i = 0; i < nums2.length; i++) 
         hs1.add(nums2[i]);
        
         hs.retainAll(hs1);
      
        int ans[]= new int[hs.size()];
    
       int i=0;
        Iterator itr = hs.iterator();
        while(itr.hasNext())
        {
            ans[i]=Integer.parseInt(itr.next().toString());
            i++;
          
        }   
      
        return ans;
    }
    

    }


Log in to reply
 

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