My code use HashMap


  • 0
    T
    public int[] intersection(int[] nums1, int[] nums2) 
    	 {
    		 
    		 
    		 if(nums1==null||nums1.length==0||nums2==null||nums2.length==0) return new int[]{};
    		 int m=nums1.length,n=nums2.length;
    		 int[] res=new int[Math.min(m, n)];
    		 HashMap<Integer, Integer>map=new HashMap<Integer, Integer>();
    		 for(int i=0;i<m;i++)
    		 {
    			 if(!map.containsKey(nums1[i])) map.put(nums1[i], i);
    		 }
    		 int index=0;
    		 for(int j=0;j<n;j++)
    		 {
    			 if(map.containsKey(nums2[j]))
    			 {
    				 res[index++]=nums2[j];
    				 map.remove(nums2[j]); //
    			 }
    		 }
    		 return Arrays.copyOfRange(res, 0, index);

Log in to reply
 

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