简体   繁体   English

减少两个嵌套for循环的时间复杂度O(N*N)

[英]Reduction of time complexity of two nested for loop O(N*N)

I am trying to reduce time complexity of the following nested loop which currently has an O(N*N) time complexity:我正在尝试降低当前具有 O(N*N) 时间复杂度的以下嵌套循环的时间复杂度:

        for(i = 0; i < N-1; i++){
            for(j = i+1; j < N; j++){
                if((A[j] > B[i])){
                    ctr++; //counting elements satisfying the condition
                }
            }
        }

A and B are just two vectors. A 和 B 只是两个向量。 I expect reducing O(N*N) to O(N).我希望将 O(N*N) 减少到 O(N)。 In addition, I doubt that if sorting A and B will help or not!另外,我怀疑排序 A 和 B 是否有帮助! Thanks!谢谢!

If you are comparing N*N/2 arbitrary elements, you need N*N/2 operations, ie O(n²).如果要比较 N*N/2 个任意元素,则需要 N*N/2 次操作,即 O(n²)。 Sorting is O(N*log(N)) and can be done separately on both vectors.排序是 O(N*log(N)) 并且可以在两个向量上单独完成。 Sorting 2 vectors is still O(N*log(N)) because constant factors do not play a role in Big-O notation.对 2 个向量进行排序仍然是 O(N*log(N)),因为常数因子在 Big-O 表示法中不起作用。

If the vectors are already sorted, you could break the loop after the first element which does not satisfy the condition.如果向量已经排序,您可以在第一个不满足条件的元素之后中断循环。

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

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