two-sum.js (609B)
1 //This is two sum hashtable solution using javascript. 2 //This algorithm has a worst case time complexity of O(n) where 3 //n is the number of values in the nums array. 4 //Time: 58ms Beats: 92.92% 5 //Memory: 42.8MB Beats: 39.35% 6 7 8 /** 9 * @param {number[]} nums 10 * @param {number} target 11 * @return {number[]} 12 */ 13 var twoSum = function(nums, target) { 14 const my_map = {}; 15 for(let i = 0 ; i < nums.length ; ++i){ 16 17 let diff = target - nums[i]; 18 if(my_map[diff] == null){ 19 my_map[nums[i]] = i; 20 } 21 else{ 22 return [i , my_map[diff]]; 23 } 24 } 25 };