方法1:双循环
var nums = [1,4,2,6,9];
var target = 7;
function twoSum(nums,target){
var arrs = [];
for(let i=0;i<nums.length;i++){
for(let j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]===target){
arrs.push(i,j);
return arrs
}
}
}
}
console.log(twoSum(nums,target)) //[0,3]
方法2:map()
<script>
//map方法
var nums = [1, 2, 3, 4, 5];
var target = 6;
var twoSum = function (nums, target) {
// let arrs =new Map()
// arrs.has()//判断键值对中是否存在该键
// arrs.get()//如果有的话 判定nums中与指定键相关联的值
// arrs.set()//给map 中添加该键值
let arrs = new Map()
// 1.对nums遍历
for (let i = 0; i < nums.length; i++) {
if (arrs.has(target - nums[i])) {
return [arrs.get(target - nums[i]), i]
}
arrs.set(nums[i], i)
}
};
console.log(twoSum(nums, target));
//bug 满足多种情况只会输出一种
</script>