const twoSum = (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]
}
}
}
}
console.log(twoSum([1,2,5,7,9], 8))
let myMap = new Map()
let arr = [1,2,5,8,10]
// console.log(myMap.has(10-2))
// console.log(myMap.set(arr[1], 1))
// console.log(myMap)
const twoSum2 = (nums, target) => {
let myMap = new Map()
for(let i = 0; i < nums.length; i++) {
// 使用Map.has()方法检查Map中是否存在带有键14,13,10,7,5 的元素。
// 另一个 目标数值
let another = target - nums[i]
if (myMap.has(another)) {
console.log(i) // nums[4]
// 使用 .get() 方法 获取 Map 中 键值 = 5 的 下标
return [myMap.get(another), i]
}
// 设置 Map 的键值 {1 => 0, 2 => 1, 5 => 2, 8 => 3}
myMap.set(nums[i], i)
}
}
console.log(twoSum2([1,2,5,8,10], 15))
console