# 两数之和(1)
# 题目
给定一个整数数组 nums
和一个目标值 target
,请你在该数组中找出和为目标值的那 两个
整数,并返回他们的数组下标
。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
# 示例
给定 nums = [2, 7, 11, 15]
, target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
# 算法
# 暴力法
遍历数组找到符合题设的值
export const twoSum = (nums, target) => {
for (let i = 0; i < nums.length - 1; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
};
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 一次遍历
每次弹出数组最后一项,然后遍历其余数组元素查找符合题设的值
export const twoSum = (nums, target) => {
while (nums.length > 1) {
const last = nums.pop();
if (nums.indexOf(target - last) > -1) {
return [nums.indexOf(target - last), nums.length];
}
}
};
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 利用数组减少复杂度
数组temp中按照temp[nums中的值] = nums中对应值的索引
存储数据,遍历数组时找到满足题设的值,然后看temp[满足题设的值]
的位置是否有值(值对应的索引),如果有返回索引;如果没有,按照约定添加新值
export const twoSum = (nums, target) => {
let temp = [];
for (let i = 0; i < nums.length; i++) {
if (temp[target - nums[i]] !== undefined) {
return [temp[target - nums[i]], i];
}
temp[nums[i]] = i;
}
};
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9