Two Sum
Last updated
Last updated
- loop thorugh the array of integers
- find the complement of the current integer
- complement = target - nums
- store complement in a Map as a key, with index with value
- [k, v] = [complement, i]
- if the current integer is found in the complement
- return current index and index of complementvar twoSum = function (nums, target) {
let map = new Map();
let result = [];
for (let i = 0; i < nums.length; i++) {
let complement = target - nums[i];
// find complement for nums[i]
if (map.has(nums[i])) {
result.push(i, map.get(nums[i]));
return result;
} else {
map.set(complement, i);
}
}
};