Skip to content

Instantly share code, notes, and snippets.

@tripolskypetr
Created December 2, 2022 08:18
Show Gist options
  • Save tripolskypetr/a06f24c601fb95895a32fc11fe2d2596 to your computer and use it in GitHub Desktop.
Save tripolskypetr/a06f24c601fb95895a32fc11fe2d2596 to your computer and use it in GitHub Desktop.
sum-of-numbers
// nums = [11,2,7,15], target = 9, out = [1,2]
// дан массива nums и int targer, необходимо вернуть индексы двух любых элементов массива, которые в сумме равны target
function TwoSum(nums = [], target){
const numsMap = new Map(
nums
.map((num, idx) => [target + num, idx])
)
for (let firstIndex = 0; firstIndex !== nums.length; firstIndex++) {
if (numsMap.has(nums[firstIndex])) {
const secondIndex = numsMap.get(nums[firstIndex]);
return [firstIndex, secondIndex];
}
}
return [-1, -1];
}
let results = TwoSum([2,7,11,15], 9);
console.log(results);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment