【发布时间】:2022-01-20 18:40:10
【问题描述】:
编写此 2sums 代码以获得有效的O(N) 时间复杂度算法以解决以下问题
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
不幸的是,数组nums 的值显示在输出中,而需要将indices 显示在输出中
下面需要做哪些改变
let hashTwoSum = (array, sum) => {
let numsObj = {}
let nums = []
for(let i in array){
let addend = sum - array[i]
if (addend in numsObj){
nums.push([addend, array[i]])
}
numsObj[array[i]] = i
}
return nums
}
let array = [2,7,11,15]
console.log(hashTwoSum(array,9))
感谢您的帮助
问候,
卡罗琳
【问题讨论】:
-
而不是将数组[i]处的值推入nums,而是推入i
-
请不要使用
for(let i in array){...}迭代数组。for/in用于迭代对象的属性,而不是数组的元素。有关原因的详细信息,请参阅此处:stackoverflow.com/questions/22754315/…。使用for/of来迭代数组的项。
标签: javascript node.js data-structures ecmascript-6