Java solution using Hashmap


  • 0
    C
     public int[] intersect(int[] nums1, int[] nums2) {
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 
            for(int i=0;i<nums1.length;i++){
                if(map.containsKey(nums1[i]))
                    map.put(nums1[i], map.get(nums1[i])+1);
                else
                    map.put(nums1[i], 1);
            }
            List<Integer> list = new ArrayList<Integer>();
            for(int i=0;i<nums2.length;i++){
                if(map.containsKey(nums2[i])){
                    list.add(nums2[i]);
                    if(map.get(nums2[i]) == 1) map.remove(nums2[i]);
                    else map.put(nums2[i], map.get(nums2[i])-1);
                }
            }
            int[] res = new int[list.size()];
            int k=0;
            for(int i=0;i<list.size();i++){
                res[k++] = list.get(i);
            }
            return res;
        }
    

Log in to reply
 

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