My java solution


  • 0
    C
         import java.util.*;
    
         public class Solution {
          public int[] intersect(int[] nums1, int[] nums2) {
    	
    	int min = nums1.length>nums2.length?nums2.length:nums1.length;
        
        if(min == 0)return new int[]{};
        
    	int [] res = new int[min];
    	
    	List<Integer> list = new ArrayList();
    	
    	int j=0;
    	
    	Hashtable<Integer,Integer> table1 = new Hashtable();
    	
    	int[]tmp = new int[]{};
    	
    	if(nums2.length>nums1.length)
    	{
    	    tmp = nums1;
    	    nums1 = nums2;
    	    nums2 = tmp;
    	}
    	
    	for(int i=0;i<nums1.length;i++)
    	{
    		Integer count = table1.get(nums1[i]);
    		if(count != null)
    		table1.put(nums1[i], ++count);
    		
    		else
    		{
    		    table1.put(nums1[i],1);
    		}
    	}
    	Integer count2 = 0;
    	for(int i=0;i<nums2.length;i++)
    	{
    		if((count2 = table1.get(nums2[i]))!=null &&((count2 = table1.get(nums2[i]))!=0))
    		{
    			res[i]++;
    			count2--;
    			table1.put(nums2[i], count2);
    			j++;
    		}
    	}
    	
    	for(int k =0;k<nums2.length;k++)
    	{
    		while(res[k] != 0)
    		{
    			list.add(nums2[k]);
    			res[k]--;
    		}
    	}
    	
    	int []result = new int[list.size()];
    	
    	for(int i=0;i<list.size();i++)
    	{
    		result[i] = list.get(i);
    	}
    	return result;
    }
    

    }


Log in to reply
 

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