方法来自题解。
- while循环
- 取数组最后一个,并用indexOf来匹配符合条件的另一个
- 返回indexOf的值和数组长度即结果
var twoSum = function(nums, target){
let i=nums.length
while(i>1){
let last=nums.pop()
if(nums.indexOf(target-last)>-1){
return[nums.indexOf(target-last),nums.length]
}
i--
}
}
利用map
var twoSum = function(nums, target) {
const map=new Map();
for(let i=0;i<nums.length;i++){
const res=target-nums[i]
if(map.has(res)){
return[map.get(res),i]
}else
map.set(nums[i],i)
}
};