JavaScript Solution, ~90ms


  • 0
    S
    function twoSum(nums, target) {
      var tmp = {}, self = target / 2
      var subs = {}, zero
      for (var i = 0; i < nums.length; i++) {
        var tmpn = tmp[nums[i]]
        if (tmpn !== undefined) {
          subs[nums[i]] = target - nums[i]
          if (subs[nums[i]] == self) {
            return [tmpn, i]
          }
          zero = i
        } else {
          tmp[nums[i]] = i
        }
      }
    
      var keys = Object.keys(tmp)
      for (var i = 0; i < keys.length; i++) {
        var t = subs[keys[i]] ? subs[keys[i]] : target - keys[i]
        if (tmp[t] !== undefined) {
          if (t == keys[i] && zero !== undefined) {
            return [tmp[keys[i]], zero]
          } else {
            return [tmp[keys[i]], tmp[t]]
          }
          
        }
      }
    }
    

Log in to reply
 

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