题目描述:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
输入:nums = [2, 7, 11, 15], target = 9
输出:[0,1]
解题思路一: 两层遍历
function twoSums(nums, target) {
for(let i = 0; i< nums.length; i++) {
for(let j=i+1; j< nums.length; j++){
if(nums[i] + nums[j]) {
return [i, j]
}
}
}
}
如果nums[i] + nums[j] === target, 返回[i,j],时间复杂度O(n^2)
解题思路二:一层遍历
求和问题一般都可以转化为求差问题
indexOf 找到另一个 target - num[i]的索引
function twoSums2(nums, target) {
for(let i = 0; i< nums.length; i++) {
let index = nums.indexOf(target - nums[i])
if (index !== -1 && index !== i) {
return [i, index]
}
}
}
解题思路三: 借助于其他的数据结构
在算法中,用空间换时间经常存在,善于利用Map、Set等数据结构,而Map的功能常常可以使用{}来实现
function twoSums3(nums, target) {
const res = {}
for (let i = 0; i< nums.length; i++) {
if(res[target - nums[i]] !== undefined) {
return [i, res[target - nums[i]]]
} else {
res[nums[i]] = i // 记录当前的索引
}
}
}