简单思路:很简单,记录一个 map,遍历数组,查看 target - cur 是否存在 map 中,再查看两个下标是否一致,就可以得出结果了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function (nums, target) {
const map = nums.reduce((res, cur, index) => {
res[cur] = index;
return res;
}, {});
for (let index = 0; index < nums.length; index++) {
const cur = nums[index];
const targetMap = map[target - cur];
if (targetMap && targetMap !== index) {
return [index, targetMap];
}
}
};
const nums = [3, 3],
target = 6;
console.log(twoSum(nums, target));