1. Two Sum

248 阅读1分钟

题目描述

leetcode-cn.com/problems/tw…

分析

暴力法肯定是很直接的,但是用 hash 可以加速,我着重介绍这部分

算法

哈希

过程

这里就不手写 HaseSet 了,直接用 JS 的 Map

map 中存什么

key:当前遍历到的 item value:索引

解释 map 的 key / value

key:在遍历数组的过程中,如果要找到另一个数使得 x + y === target,如果当前遍历到的是 x,那么实际上需要找 y,所以 map 中的 key 一定是另一个 item

value:看题目要求,返回的是 index pair,所以 value 如果是 index 的话,只需要把当前索引和 y 的索引构建成数组,直接返回就可以了,因此 value 是根据题目要求决定的,他应该是 index

代码

/**
 * @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 x = nums[i]
    const pair = map.get(target - x)
    if (pair !== undefined) return [pair, i]
    map.set(x, i)
  }
}