Last active
September 25, 2021 08:34
-
-
Save midorikocak/4047b66e6d7e3fb451427bf9cba4dc59 to your computer and use it in GitHub Desktop.
Two Sums
This file contains 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
// https://leetcode.com/problems/two-sum/ | |
/** | |
* @param {number[]} nums | |
* @param {number} target | |
* @return {number[]} | |
*/ | |
var twoSum = function(nums, target) { | |
/* First Solution (Brute Force) | |
let indexes = []; | |
for(let i=0; i<nums.length; i++){ | |
for(let j= i + 1; j<nums.length; j++){ | |
if((nums[i] + nums[j]) == target){ | |
indexes = [i, j]; | |
return indexes; | |
} | |
} | |
} | |
*/ | |
// num > 0 ? num : num * -1 | |
// if (num > 0 ) {return num; } else {return (num * -1); } | |
// Math.abs(n) == (n > 0 ? n : n * -1) | |
// nums = [2, 7, 11, 15] | |
// subs = [7, 2, 2, 6] | |
/* This is a trap!!! | |
let subtracts = nums.map( num => Math.abs(num - target)); | |
for (let i = 0; i< nums.length; i++){ | |
let j = subtracts.indexOf(nums[i]); | |
if(j !== -1){ | |
return [i,j]; | |
} | |
} | |
*/ | |
/* | |
let dictionary = { | |
pen: 'boli', | |
paper : 'papel', | |
notebook: 'libreta', | |
eraser: 'goma' | |
}; | |
console.log(dictionary['tomato']) | |
*/ | |
let substDict = {} | |
let solutions = []; | |
for(let i=0; i < nums.length; i++){ | |
let subst = target - nums[i]; | |
substDict[subst] = i; | |
} | |
for(let j = 0; j < nums.length; j++){ | |
if(substDict[nums[j]] !== undefined){ | |
let secondIndex = substDict[nums[j]]; | |
return [j, secondIndex ]; | |
} | |
} | |
return solutions; | |
// 1. if there is more solutions, add that to solutions array nums = [2,7,4,5] target = 9 | |
// 2. remove duplicates [[0,1], [1,0]] | |
// 3. Why this is not working? nums = [3,2,4] target = 6 | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment