7 ms Java Solution using HashMap


  • 1

    public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {

        int ans[]=new int[Math.min(nums1.length,nums2.length)];
        
        if(nums1.length==0||nums2.length==0)
         return ans;
      
        HashMap <Integer,Integer>hm=new HashMap <Integer,Integer>();
        for(int i=0;i<nums1.length;i++){
          if(hm.containsKey(nums1[i])){
          hm.put(nums1[i],hm.get(nums1[i])+1);
          }
          else{
          hm.put(nums1[i],1);
          }
        }
            int j=-1;
            Iterator it = hm.entrySet().iterator();
    
           
           for(int i=0;i<nums2.length;i++){
           if(hm.containsKey(nums2[i]))   {   
                    if(hm.get(nums2[i])>=1){
                      //  System.out.println("aaaya"+nums2[i]);
                   ans[++j]=nums2[i];
                
                hm.put(nums2[i],hm.get(nums2[i])-1);
           }
           }
               
           }
        
       int d[]=new int[j+1];
             System.arraycopy(ans, 0, d, 0, j+1);
         return d;  
            
        }
        
    }

Log in to reply
 

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