在数组中找到两数之和为 target --
2019-11-21 本文已影响0人
Joah_l
function twoSum2(nums, target) {
// 查找 hash table
let obj = {}
for (let i = 0, len = nums.length; i < len; i++) {
let item = nums[i]
let j = target - item
if (typeof obj[j] !== 'undefined') {
return [obj[j], i]
}
obj[item] = i
}
return ''
}
const r = twoSum2([1, 3, 4, 2, 1], 2)
console.log(r)