Javascript hashmap counter


  • 0
    J

    Pretty simple, count the frequency of the numbers, if frequency === 1, this means we've seen it twice.

    /**
     * @param {number[]} nums
     * @return {number[]}
     */
    var findDuplicates = function(nums) {
        const numHash = new Map();
        const res = [];
        
        for (let i = 0; i < nums.length; i++) {
            if (numHash.has(nums[i])) {
                let count = numHash.get(nums[i]) + 1;
                numHash.set(nums[i], count)
            } else {
                numHash.set(nums[i], 0)
            }
        }
        
        numHash.forEach((val, key) => {
            if (val === 1) {
                res.push(key)
            }
        });
        
        return res;
    };

Log in to reply
 

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