1-题目
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1]
2- 解题思路整理
01- 暴力for循环
时间复杂度:O(N2)
空间复杂度:O(1)
解题思路:nums中的每一个数都和其后面的每一项相加与target进行比较
var twoSum = function(nums, target) {
let res = []
if(!Array.isArray(nums)||nums.length < 2){
return res
}
for(let i = 0; i < nums.length; i++){
for(j = i + 1; j < nums.length; j++){
if(Number(nums[i]) + Number(nums[j]) === Number(target)){
res = [i,j]
return res
}
}
}
return res
};
02- 哈希表
时间复杂度:O(n)
空间复杂度:O(n)
解题思路:
1- 设计哈希表:哈希表的key为数组中的每一个值,哈希表的value是该值在数组中的下标;
2- 创建哈希表:遍历数组nums,将nums中的值和下标放入哈希表中;
3- 再次遍历nums,当前遍历到的每一项constrackNum,查看创建好的哈希表中是否有target - constrackNum 对应的key,
·如果没有找到,则此次循环结束,继续进行后续循环操作
·如果有,判断该下标是否与constrackNum对应的下标一致,如果一直,此次循环结束,执行后续循环操作
·如果有,且该下标不是constrackNum对应的下标,小下标在前,大下标在后返回数据
var twoSum = function(nums, target) {
let res = []
if(!Array.isArray(nums)||nums.length < 2){
return res
}
let tmpMap = new Map()
nums.forEach((item,index) => {
tmpMap.set(item,index)
})
for(let i = 0; i < nums.length; i++){
const constrackNum = nums[i]
const diffIndex = tmpMap.get(target - constrackNum)
if(diffIndex && diffIndex !== i){
res = [
Math.min(i,diffIndex),
Math.max(i,diffIndex)
]
}
}
return res
};
05- 双指针
时间复杂度:
空间复杂度:
解题思路整理:
var twoSum = function(nums, target) {
if (
!Array.isArray(nums) ||
nums.length === 0
) {
return []
}
const numsWithIndex = nums
.map((num, index) => {
return {
value: num,
index,
}
}).sort((numOne, numTwo) => numOne.value - numTwo.value)
let left = 0
let right = numsWithIndex.length - 1
while (left < right) {
const sum = numsWithIndex[left].value + numsWithIndex[right].value
if (sum < target) {
left++
} else if (sum > target) {
right--
} else {
return [
Math.min(numsWithIndex[left].index, numsWithIndex[right].index),
Math.max(numsWithIndex[left].index, numsWithIndex[right].index)
]
}
}
return []
};