1-基础版两数之和
const twoSum = function (nums, target) {
const map = {}
for (let i = nums.length - 1; i >= 0; i--) {
if (map[nums[i]] !== undefined) {
return [i, map[nums[i]]]
} else {
map[target - nums[i]] = i
}
}
}
console.log(twoSum([1, 2, 2, 3], 4))
2-查出全部符合的两数之和(输出下标)
const allTwoSum = function (nums, target) {
const res = []
const map = {}
for (let i = nums.length - 1
if (map[nums[i]] !== undefined) {
res.push([i, map[nums[i]]]) // 存下标
} else {
map[target - nums[i]] = i // 存下标
}
}
return res
}
console.log(allTwoSum([1, 2, 2, 3], 4)) // [ [ 1, 2 ], [ 0, 3 ] ]
3-三数之和(输出下标)
const allThreeSum = function (nums, target) {
const res = []
for (let i = nums.length - 1; i >= 0; i--) {
const diff = target - nums[i]
const twoSumResult = allTwoSum(nums.slice(0, i), diff)
if (twoSumResult.length) {
twoSumResult.forEach(arr => res.push([i, ...arr]))
}
}
return res
}
console.log(allThreeSum([1, 2, 2, 3], 6))
(号外)js API 求 两数之和
const allTwoSum = function (nums, target) {
const res = []
for (let i = nums.length - 1
const diff = target - nums[i]
const idx = nums.slice(0, i).findIndex(o => o === diff)
if (idx > -1) {
res.push([i, idx])
}
}
return res
}
console.log(allTwoSum([1, 2, 2, 3], 4)) // [ [ 3, 0 ], [ 2, 1 ] ]