简体   繁体   English

Node JS在索引而不是索引处显示值

[英]Node JS displaying value at index instead of indices

Written this 2sums code to get efficent O(N) Time complexity algorithm for below problem编写此 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].

unfortunately saw value at array nums got displayed in the output,whereas the need is to get the indices to be displayed in output不幸的是,数组nums的值显示在 output 中,而需要让indices显示在 output 中

What change needs to be done below下面需要做哪些改变

            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))
            
            

Your help is appreciated感谢您的帮助

Regards,问候,

Carolyn卡罗琳

As @jriend00 said, do not use for(... in...) loop for iterating arrays.正如@jriend00 所说,不要使用for(... in...)循环来迭代 arrays。 But in your case, where you need indices, you need to use the good old for loop: for(let i = 0; i < array.length; i++) .但是在您需要索引的情况下,您需要使用旧for循环: for(let i = 0; i < array.length; i++) And when you save results, you need to push both indices : nums.push([numsObj[addend], i]) .当您保存结果时,您需要推送两个索引nums.push([numsObj[addend], i])

Here's a complete example:这是一个完整的例子:

let hashTwoSum = (array, sum) => {
    let numsObj = {}
    let nums = []

    for(let i = 0; i < array.length; i++){
        let addend = sum - array[i]

        if (addend in numsObj){
            nums.push([numsObj[addend], i])
        }
        numsObj[array[i]] = i
    }
    return nums
}

let array = [2,7,11,15,6]
console.log(hashTwoSum(array,17))

This will output:这将 output:

[ [ 0, 3 ], [ 2, 4 ] ]

because 2 + 15 and 11 + 6 are both equal 17.因为 2 + 15 和 11 + 6 都等于 17。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM