两数之和

通过设置字典,保存之前的结果,如果在之前的结果中找到,返回即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function (nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const _target = target - nums[i];
if (map.has(_target)) {
return [map.get(_target), i];
} else {
map.set(nums[i], i);
}
}
};

本站由 ao 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。