两数之和
给定一个整数数组 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]
我的思路:利用nums循环,然后根据target减去nums中每一个元素的值,利用indexOf去查询这个值是否在nums中,并且判断indexOf返回的值是否和nums的下标一致,最后去重。
网上思路:利用map()
1.我的思路:利用indexOf
var twoSum = function (nums, target) {
let arr = [];
let a = nums
nums.forEach((item, index) => {
if (a.indexOf(target - item) !== -1 && index !== a.indexOf(target - item)) {
arr.push(index, a.indexOf(target - item))
}
})
return [...new Set(arr)]
};
// 优化了一下,因为相加的话,只可能有2个数,因为说了不能重复
var twoSum = function (nums, target) {
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
const j = nums.indexOf(complement);
if (j !== -1 && j !== i) {
return [i, j]
}
}
};
2.利用Map对象
var twoSum = function (nums, target) {
const numMap = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (numMap.has(complement)) {
return [numMap.get(complement), i];
}
numMap.set(nums[i], i);
}
return []
};
3.双重循环
var twoSum = function (nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
};
4.利用findIndex
var twoSum = function (nums, target) {
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
const j = nums.findIndex((num, index) => num === complement && index !== i);
if (j !== -1) {
return [i, j];
}
}
};