「No.01」【 每日壹题 】
Visionwuwu 2021-01-23
算法
javascript
LeetCode算法题之-俩数之和
# LeetCode算法题之-俩数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
你可以按任意顺序返回答案
# 示例
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
1
2
3
2
3
# 思路
- 创建一个map,以nums[i]为key,索引i为value存储nums数组中的数
- for循环遍历nums数组
- 用taget减去nums[i],以计算哪个数与nums[i]相加等于target
- 检查map中有没有这个数,如果有返回结果,没有就将nums[i]为key,i为value存放到map中
# 动图解析

# 参考答案
利用Map存储
const nums = [2,7,11,15], target = 9
function twoNumWithMap (target, nums) {
const map = new Map()
for (let i = 0; i < nums.length; i++) {
const targetNumber = target - nums[i]
if (!map.has(targetNumber)) {
map.set(nums[i], i)
} else {
return [map.get(targetNumber), i]
}
}
return []
}
const result = addTwoNumWithMap(target, nums)
console.log(result)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
利用对象存储
const nums = [2,7,11,15], target = 9
function addTwoNumWithObj (target, nums) {
const obj = {}
for (let i = 0; i < nums.length; i++) {
const targetNumber = target - nums[i]
const targetIndex = obj[targetNumber]
if (targetIndex === undefined) {
obj[nums[i]] = i
} else {
return [targetIndex, i]
}
}
return []
}
const result = addTwoNumWithMap(target, nums)
console.log(result)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16