通过设置字典,保存之前的结果,如果在之前的结果中找到,返回即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
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); } } };
|