//求数组[15,11,2,7]中两数之和为9的索引数组,即返回[2,3]
//哈希法
var two_number_sum = function(arr,target){
var map=new Map();
var result = [];
for(let i in arr){
map.set(arr[i],i);
}
for(let i in arr){
var diff=target-arr[i];
if(map.get(diff)&&map.get(diff)!==i){
console.log(diff);
result[0]=i;
result[1]=map.get(diff);
return result;
}
}
return result;
}
var a=[15,11,2,7],target=9;
console.log(two_number_sum(a,target));
//总结:之前一直用双指针,其实按照数据结构的知识点,哈希表是最好理解,和底层逻辑对应最直接高效的,学习了
// for in 遍历数组得到的是数组下标,for of遍历数组得到的数组的元素项
1.两数相加
于 2022-05-17 22:31:50 首次发布