Skip to content

Instantly share code, notes, and snippets.

@lienista
Last active October 11, 2018 22:59
Show Gist options
  • Select an option

  • Save lienista/f206fbb8ad713832696a989a36d1074b to your computer and use it in GitHub Desktop.

Select an option

Save lienista/f206fbb8ad713832696a989a36d1074b to your computer and use it in GitHub Desktop.
Algorithms in Javascript: Leetcode 1. Two Sum - Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
const twoSum = (a, target) => {
let len = a.length;
if(a.length === 2) return [0, 1];
for(let i=0; i<len; i++) {
for (let j = i + 1; j < len; j++) {
if(a[j] === target - a[i]) {
return [i,j];
}
}
}
}
console.log(twoSum([1,2,3,4,5,6,7], 13));
console.log(twoSum([3,2,4], 6));
console.log(twoSum([3,3], 6));
console.log(twoSum([3,2,3], 6))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment