题解 | #两数之和#
两数之和
http://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
function twoSum( numbers , target ) {
let map = new Map(), res = new Array(2)
for(let i = 0 ; i < numbers.length ; i++){
let diff = target - numbers[i]
if(map.has(diff)){
// 注意判断顺序问题,diff已在map中存在,即diff在前
// 同时,还要注意数组下标从1开始
res[0] = map.get(diff) + 1
res[1] = i + 1
break
}else {
map.set(numbers[i] , i)
}
}
return res
}
module.exports = {
twoSum : twoSum
};