简体   繁体   中英

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:

        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. I expect reducing O(N*N) to O(N). In addition, I doubt that if sorting A and B will help or not! Thanks!

If you are comparing N*N/2 arbitrary elements, you need N*N/2 operations, ie O(n²). Sorting is O(N*log(N)) and can be done separately on both vectors. Sorting 2 vectors is still O(N*log(N)) because constant factors do not play a role in Big-O notation.

If the vectors are already sorted, you could break the loop after the first element which does not satisfy the condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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