简体   繁体   English

阅读二维数组行为问题?

[英]reading 2D array behavior issue?

Test Cases:测试用例:

(6, [1,3,2,6,1,2]) returns (pairs / 2) = 5

It does get the answer the thing is that is doing more than it needs to, It is possible just add some validation to know when he is adding same reversed index but it will only give it more to do.它确实得到了答案,那就是做的比它需要的更多,有可能只添加一些验证来知道他何时添加相同的反向索引,但这只会给它更多的工作。 am looking to remove the unneeded work.我正在寻找删除不需要的工作。 can it be more reliable?它可以更可靠吗?

function returnOcurrences(k,ar){
    debugger;
    const letters = [new Set(ar)];
    let pairs = 0;

    for (let i = 0; i < ar.length; i++) {
        for (let ii = 0; ii < ar.length; ii++) {
            let a = ar[i] + ar[ii];
            if (i != ii) {
                if (a >= k) {
                    pairs += (a % k == 0) ? 1 : 0
                }
            }
        }
    }
    return pairs/2;
}

What I assume you want to do is prevent the algorithm from checking eg ar[1] + ar[2] , then ar[2] + ar[1] again.我假设您想要做的是阻止算法检查例如ar[1] + ar[2] ,然后再次检查ar[2] + ar[1]

To solve this, consider starting your inner loop from i + 1 and not from 0. This prevents the mentioned scenario from happening, and also prevents the algorithm from summing an element with itself (eg ar[0] + ar[0] ).要解决此问题,请考虑从i + 1而不是从 0 开始您的内部循环。这可以防止上述情况发生,并且还可以防止算法将元素与自身相加(例如ar[0] + ar[0] )。 So no need to check anymore if i is equal to ii .所以不需要再检查i是否等于ii

Why so?为什么这样? Assume the first iteration of the outer loop.假设外循环的第一次迭代。 You are checking the sum of ar[0] with ar[1] , then with ar[2] , ar[3] , and so on.您正在检查 ar[0] 与ar[1]的总和,然后是ar[2]ar[3] ,依此类推。

On the second iteration of the outer loop, you are checking sums of ar[1] with other elements of the array.在外循环的第二次迭代中,您正在检查ar[1]与数组其他元素的总和。 However, you already checked ar[0] + ar[1] in the previous iteration.但是,您已经在上一次迭代中检查了ar[0] + ar[1] So you start with ar[1] + ar[2] , where ii = i + 1 = 2 .所以你从ar[1] + ar[2] ,其中ii = i + 1 = 2

So the code becomes:所以代码变成了:

function returnOcurrences(k,ar){
    const letters = [new Set(ar)]; //I don't see the purpose of this variable but okay
    var pairs = 0;

    for (var i = 0; i < ar.length; i++) {
        for (var ii = i + 1; ii < ar.length; ii++) {
            var a = ar[i] + ar[ii];
                if (a >= k) {
                    pairs += (a % k == 0) ? 1 : 0
                }
        }
    }
    return pairs/2;
} 

Hope this helps!希望这可以帮助!

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

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