前言声明
- 来源:力扣(LeetCode)
- 链接:leetcode-cn.com/problems/tw…
两数之和
- 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
- 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
- 你可以按任意顺序返回答案。
Example 1:
输入:nums = [2, 4, 6, 8], target = 10
输出:[1, 2]
解释:因为 nums[1] + nums[2] == 10 ,返回 [1, 2]
Example 2:
输入:nums = [1, 2, 3, 4, 9], target = 7
输出:[2, 3]
解释:因为 nums[2] + nums[3] == 7 ,返回 [2, 3]
提示:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
只会存在一个有效答案
- 进阶:你可以想出一个时间复杂度小于 O(n2) 的算法吗?
Solving Ideas
const twoSum = function (nums, target) {
// 用于保存遍历过的数据
const hash = {}
// 遍历数组
for (let i = 0; i < nums.length; i++){
// 判断hash中第二个值是否存在数组中
if (hash[target - nums[i]] != undefined) {
// 一旦存在就返回最近符合的数组下标
return [hash[target - nums[i]], i]
}
// 将遍历过的元素以 key:value 保存在 hash 中
hash[nums[i]] = i
}
// 没有找到就返回空数组
return []
}
twoSum([1, 2, 3, 5, 4], 8) // [2, 3]
twoSum([11, 22, 33, 44], 99) // []