Javascript hashmap in es6


  • 1
    J

    Uses map object to hold the values we are looking for, and sets the key value as the index. When we find the number we're looking for, we return the index of the item (i) and our saved index

    var twoSum = function(nums, target) {
        const hashMap = new Map();
        const result = [];
        
        for (let i = 0; i < nums.length; i++) {
            if (hashMap.has(nums[i])) {
                result.push(i, hashMap.get(nums[i]))
            } else {
                let sumVal = target - nums[i];
                hashMap.set(sumVal, i);
            }
        }
        
        return result;
    };

  • 0

    Cool! Mine uses similar logic, except, I use a traditional Javascript object to keep track of values. Also, your code runs in around 92ms, while mine does so in 102ms. Maps are clearly faster.

    var twoSum = function(nums, target) {
        var tracker = {};
        for(var i=0; i<nums.length; i++) {
            if (tracker[target - nums[i]]) {
                return [tracker[target-nums[i]], i+1];
            } else {
                tracker[nums[i]] = i+1;
            }
        }
        return [];
    };
    

Log in to reply
 

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