My Simple Javascript Solution


  • 10
    Y
    var twoSum = function(nums, target) {
        var ret = [];
        var exist = {};
        for(var i = 0; i < nums.length; i++){
            if(typeof(exist[target - nums[i]]) !== 'undefined'){
                ret.push(exist[target - nums[i]]);
                ret.push(i + 1);
            }
            
            exist[nums[i]] = i + 1;
        }
        
        return ret
    };

  • 1
    N

    I don't think this will work. I tried, it cannot pass and get "wrong answer"


  • 0
    D

    @yinsheng This should be a wrong answer.


  • 3
    H

    The correct answer would be

    var twoSum = function(nums, target) {
    var ans = [];
    var exist = {};
    
    for (var i = 0; i < nums.length; i++){
        if (typeof(exist[target-nums[i]]) !== 'undefined'){
            ans.push(exist[target-nums[i]]);
            ans.push(i);
        }
        exist[nums[i]] = i;
    }
    
    return ans;
    

    };


  • 0
    X

    my solution is:

    function twoSum(nums, target) {
      var result = []
      nums.forEach(function(num, i) {
        var diff = target - num
        var k = nums.indexOf(diff)
        if (k > -1 && k !== i) {
           result[0] = i
           result[1] = k
           return true
        }
      })
      return result
    }
    

Log in to reply
 

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