简体   繁体   中英

Why is the runtime for this code O(N^2) when using a linked list?

So, for data structures here is a piece of code we are supposed to find the runtime for:

public static int calc( List<Integer> lst )
      {

         int count = 0;
         int N = lst.size();

         for ( int i=0; i<N; i++)
         {
            if (lst.get(i) > 0)
               sum += lst.get(i);
            else
               sum += lst.get(i) * lst.get(i);
         }
         return sum;
      } 

We are supposed to answer what the runtime would be if lst is a LinkedList vs an ArrayList . So for an array it is pretty easy, just O(N) because it loops through the list checking every element, and lst.get(i) is a constant time operation since it is an array. The tricky part is over a linked list. From what I'm seeing, every time lst.get(i) would be called on a linked list, it would have to start at the head of the list and traverse to index i. And from this code it looks like it would call get either 3 times or 2 times depending on the result of the if statement, so I would think it would be O(N^4) / O(N^3) runtime. However, according to a grad student, it is O(N^2) time. Just wondering if someone can explain what the correct answer is and why.

I ran some test code on java and got this as my time result: list 1 is elements 0 - 99 of size 100. And list 2 is elements 0 - 9999, of size 10,000 List one finished in 2868 ms, list two finished in 99443 ms.

There are at worst 3 get operations for every loop iteration. For LinkedList , a get operation is O(N) because you have to walk the list. As such, there at worst 3 * O(N) operations, at worst N times. Hence, O(N^2) .

However, it can be made as efficient for LinkedList as ArrayList - and simpler - by using an enhanced for loop:

for (int e : lst) {
  if (e > 0)
    sum += e;
  else
    sum += e * e;
}

This internally uses an Iterator , which isn't O(N) to look up each element for LinkedList , because it keeps track of where it is: getting the next element from the Iterator is just O(1) .

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