Problem
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Solution
直接的方式
const twoSum = (source, target) => {for (let i = 0; i < source.length - 1; i++) {for (let j = i + 1; j < source.length; j++) {if (source[i] + source[j] === target) {return [i, j];}}}return [-1, -1];};
使用空间换时间, 时间效率为O(n), 空间效率为O(n)
const twoSum = (source, target) => { const numMap = new Map(); for (let i = 0; i < source.length; i++) { numMap.set(source[i], i); } for (let i = 0; i < source.length; i++) { const objNum = target - source[i]; if (numMap.has(objNum) && numMap.get(objNum) !== i) { return [i, numMap.get(objNum)]; } } return [-1, -1]; };
