Skip to content

Instantly share code, notes, and snippets.

@LottieVixen
Last active November 13, 2020 11:23
Show Gist options
  • Save LottieVixen/58ede10042383bea1f9473319288477c to your computer and use it in GitHub Desktop.
Save LottieVixen/58ede10042383bea1f9473319288477c to your computer and use it in GitHub Desktop.

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target

example

Input: nums = [2,7,11,15], target = 9
Output: [0,1]

Because nums[0] + nums[1] == 9, we return [0, 1].

//a lot of the faster look like this
var twoSum = function(nums, target) {
let map = new Map();
for (let i = 0; i < nums.length; i++) {
if (map[target - nums[i]] !== undefined) {
return [map[target - nums[i]], i];
}
map[nums[i]] = i;
}
};
var twoSum = function(nums, target) {
const obj = {}
for(let i = 0; i <nums.length; i++){
if (obj[nums[i]] >=0){
return [obj[nums[i]],i]
}
obj[target-nums[i]] = i
}
};
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
var result = [];
for ( var i = 0; i < nums.length; i++){
var searchFor = target - nums[i];
var idx = nums.indexOf(searchFor,i+1);
if (idx !== -1){
//if index found
result.push(i);
result.push(idx);
} else {
//else continue
continue;
}
//result found, break
break;
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment