简体   繁体   中英

Time Complexity of Simple Algo

I'm trying to figure out the running time of the code below.

If add and trimToSize are both O(n), the interior of the block would run in 2N time, and then since the loop takes N time, the whole program would run in N*(2N) time?... O(n^2)?

ArrayList a = new ArrayList();

for (int i = 0; i< N; i++){
    a.add(i);
    a.trimToSize();
}

Yes. But ArrayList#add is usually O(1) except for the case when the internal storage array has to be increased.

If you want to optimize your code, do it as follows:

ArrayList a = new ArrayList(N); // reserve space for N elements

for (int i = 0; i < N; i++) {
    a.add(i); // O(1)
}

// no need for trimToSize

This now has only O(n) !

You are correct, it would be O(n^2). The for loop executes N times, and like you said, add and trimToSize take O(n) time, so it would be:

N * (N + N) = N * (2N) = 2 * N^2

but the constant factor of 2 does not matter for big-O notation because the n^2 is the dominating part of the function. Therefore, it is O(n^2).

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