简体   繁体   中英

What's the time complexity for the loops?

thelist = [[2,3],[],[]]
n=len(thelist)
for i in range(1,n):
    if i <= k:
        thelist[i].append(1)
        for j in thelist[i-1]:
            c = j+1
            thelist[i].append(c)

I am trying to figure out the time complexity for the code. Isit O(n^2) or O(n)? I think it's O(n^2) because there's 2 loops but then again I'm not using n times to run the 2nd loop so it might be O(n). I trying to get the time complexity of O(n).

  • Amount of items we iterate through in thelist is n-1
  • Amount of items in the sublist before the main list you're iterating through will be 2 for the first iteration, then +1 every time (2, 3, 4, ..., n, n+1). However, we can ignore the n+1 since we won't be iterating through that. So, worst case we iterate through n times.

Hence it's O((n-1)*n) , which we generally just round to 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