Javascript two sum

  • 3
    1. Walk through the array saving off what the current entry would need to
      fulfill the target and the current index in the array
    2. As you walk the array if you find a previously saved entry is looking for the current array value then you have found the match.

    Note: this is based on the popular java solutions. I didn't come up with this strategy on my own.

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

  • 0

    Some lines end with ; will some lines not. Bad code style.

  • 0

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

Log in to reply

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