题解 | #和为S的两个数字#
和为S的两个数字
https://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b
function FindNumbersWithSum(array, sum) { // 方法一:双循环暴力解法,运行超时 // for(let i = 0; i < array.length; i++){ // for(let j = i + 1; j < array.length; j++){ // if(array[i] + array[j] === sum){ // return [array[i], array[j]]; // } // } // } // return []; // 方法二:哈希表 // 对于数组中每个数a,用sum减去a剩余b,如果b在数组中已经出现过了,则a,b就是我们要找的 // 哈希表的键为数组值,键值为其下标 const map = new Map(); let temp = 0; for (let i = 0; i < array.length; i++) { // 计算减去当前元素后需要的元素的值temp temp = sum - array[i]; // 判断当前map中是否有需要的元素值temp // 如果有直接返回当前元素和需要的元素值temp if (map.has(temp)) { return [array[map.get(temp)], array[i]]; } // 将当前元素加入到map中 map.set(array[i], i); } return []; } module.exports = { FindNumbersWithSum: FindNumbersWithSum, };