My Simple Javascript Solution


  • 11
    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.


  • 4
    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;
    

    };


  • 1
    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
    }
    

  • 0
    W

    var twoSum = function(nums, target) {
    var number = {};
    var numm = []
    var i = 0;
    while(i < nums.length) {
    number[nums[i]] = [i,target - nums[i]]
    if(number[target - nums[i]]&&number[target - nums[i]][0]!=i) {
    numm[0] = number[target - nums[i]][0]
    numm[1] = i
    break;
    }
    i++;
    }
    return numm;
    }
    the answer is right,but... if the array is [3,3],target = 6. emm, i get [ ]... because object can`t have a repeat member.


Log in to reply
 

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