My javascript solution for two sum


  • 0
    U
    var twoSum = function(nums, target) {
        var result = null;
        var hash = {};
        var hash1 = {};
        nums.forEach(function (item,i) {
            if(!hash[item]) {hash[item] = [];}
            hash[item].push(i);
            hash1[i] = item;
        })
        nums.forEach(function (item,i) {
            var find = target - item;
            if(hash[find]){
                var indices = hash[find];
                indices.forEach(function (index) {
                    if(hash1[i] + hash1[index] == target && i != index){
                        result = [index,i];
                    }
                });
            }
        });
        return result;
    };

Log in to reply
 

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