两数之和

62 阅读1分钟

两数之和

记录一下算法题,这是lecode上面的一道算法

image.png

解题思路

利用Map数据结构,这种方法只需要循环一次即可

const num = [1, 2, 8, 4, 5]
const target = 9
const map = new Map()

function getIndex(num, target) {
  return num.reduce((acc, curr, i) => {
    // 获取目标和当前数的差数
    const deviations = target - curr
    // 判断map是否有差数,有的话就添加到数组
    if (map.has(deviations)) {
      acc.push([map.get(deviations), i])
    }
    // 将值设置为map的key,下表设置为map的value
    map.set(curr, i)
    return acc
  }, [])
}

console.log(getIndex(num, target))
// [ [ 0, 2 ], [ 3, 4 ] ]