clueless coding // TODO: be smarter

LeetCode Intersection of Two Arrays II: Java Solution



TL;DR Code Solution


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

    HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
    List<Integer> res = new ArrayList<Integer>();

    for (int i = 0; i < nums1.length; i++) {
        hashMap.put(nums1[i], hashMap.getOrDefault(nums1[i], 0) + 1);
    }

    for (int i = 0; i < nums2.length; i++) {
        if (hashMap.containsKey(nums2[i]) && hashMap.get(nums2[i]) > 0) {
            res.add(nums2[i]);
            hashMap.put(nums2[i], hashMap.get(nums2[i]) - 1);
        }
    }

    int[] arr = new int[res.size()];
    for (int i = 0; i < res.size(); i++) {
        arr[i] = res.get(i);
    }


    return arr;


}