Created
August 7, 2019 20:04
-
-
Save tombaranowicz/be9ef93be5a42d0b25358bdad52b6d2a to your computer and use it in GitHub Desktop.
2 ways of solving "Two Sum" coding interview problem in JavaScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// var twoSum = function(nums, target) { | |
// for(index = 0; index < nums.length - 1; index++) { | |
// for(i = index+1; i< nums.length; i++) { | |
// let sum = nums[index] + nums[i]; | |
// if (sum == target) { | |
// return [index, i]; | |
// } | |
// } | |
// } | |
// }; | |
var twoSum = function(nums, target) { | |
let d = {}; | |
for(i = 0; i< nums.length; i++) { | |
if (d[target-nums[i]] >= 0) { | |
return [d[target-nums[i]], i]; | |
} | |
d[nums[i]] = i; | |
} | |
}; | |
const nums = [2, 7, 11, 15]; | |
const target = 9; | |
console.log(twoSum(nums, target)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment