简体   繁体   中英

Big-O characterization questions - java

Hi I was solving this problem, but I'm kind of stuck to choose which one is the right answer. So, I'm trying to get a help from you guys.

Here is the code:

 for (int i=0; i < n; i++) { // loop1 from 0 to n-1
    int total = 0;
    for (int j=0; j < n; j++) // loop2 from 0 to n-1
        for (int k=0; k <= j; k++) // loop3 from 0 to j
        total += first[k];
    if (second[i] == total) count++;
} return count;

From above code, loop1 and loop2 have n times n which has n^2 complex processing time

but the problem is loop3, I really don't want to say that has n times also since the limit of the loop is j not n.

In the worst time case, how should I conclude the complexity? will it going to be ((n+1)(n+2))/2 only for loop3? or ((n+1)(n+2))/2 for loop2 and loop3

My final answers are like this

first case: n * n * (((n+1)(n+2))/2) = O(n^4)

second case: n * (((n+1)(n+2))/2) = O(n^3)

which one will be the correct one? Or did I get both wrong?

ps please mind loop3 is 0 to j, not 0 to j-1

It is not clear from the question that what are the different cases you are concerned about. While discussing Big O, we only care about the most significant portion of complexity. Here j in the third loop can go up to n , as per the second loop. Hence there is no problem substituting it with n when calculating the total complexity. Since there are 3 loops in all, all directly or indirectly dependent on n , the complexity would be O(n^3) . Also, you could ignore constants, so n-1 could be simply considered as n .

See

https://stackoverflow.com/a/487278/945214

Big-O for Eight Year Olds?

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