- 时间:2022-04-12
- 题目链接:https://leetcode.com/problems/two-sum/
- tag:
数组
哈希表
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1]
示例2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例3:
输入:nums = [3,3], target = 6
输出:[0,1]
提示:
$2 <= nums.length <= 104$ $10^9 <= nums[i] <= 10^9$ $10^9 <= target <= 10^9$ - 只会存在一个有效答案
进阶: 你可以想出一个时间复杂度小于 O(n2) 的算法吗?
- 暴力穷举:每个元素和其他元素的和是否为目标值(两个指针逐个往后)
- 从中发现:循环中已经扫描过的数再重复扫描了,减少不必要重复的扫描 → 哈希表(存储每个数对应的下标值)
- 一个指针逐个扫描,计算当前值与目标值的差值去map内查找
- 找到,则输出答案
- 找不到,存储当前值,继续查找下一个
function twoSum(nums, target) {
let result = new Array(2)
for (let i = 0, len = nums.length; i < len; i++) {
for (let j = i + 1; j < len; j++) {
if (nums[i] + nums[j] == target) {
result[0] = i
result[1] = j
return result
}
}
}
}
function twoSum(nums, target) {
let result = new Array(2)
// key 为元素值,value 为对应下标
let map = new Map()
for (let i = 0, len = nums.length; i < len; i++) {
const item = nums[i]
const another = target - item
const anotherIndex = map.get(another)
if (anotherIndex !== undefined) {
result[0] = anotherIndex
result[1] = i
return result
} else {
map.set(item, i)
}
}
}
也可以存储 another,当前值与目标值的差值,道理是一样的
function twoSum(nums, target) {
let result = new Array(2)
let map = new Map()
for (let i = 0, len = nums.length; i < len; i++) {
const item = nums[i]
const another = target - item
const anotherIndex = map.get(item) // item
if (anotherIndex !== undefined) {
result[0] = anotherIndex
result[1] = i
return result
} else {
map.set(another, i) // another
}
}
}