Accepted JavaScript O(n) Solution Using an Object


  • 0
    M
     var twoSum = function(nums, target) {
         var numsObject = {};
         for (var i=0; i<nums.length; i++) {
             var num = "" + nums[i];
             numsObject[num] = i;
         }
         for (var i=0; i<nums.length; i++) {
             var complement = target - nums[i];
             if (numsObject.hasOwnProperty(complement.toString()) &&
                 numsObject[complement.toString()] != i) {
                     return [i, numsObject[complement.toString()]];
                 }
         }
    };
    twoSum([2, 7, 11, 15], 9);
    

Log in to reply
 

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