Algorithmic complexity of naive code for processing all consecutive subsequences of a list: n^2 or n^3?

前端 未结 9 1092
傲寒
傲寒 2020-12-25 11:41

I\'m studying for a test and found this question:

I can\'t really determine the complexity, I figured it\'s either O(n2) or O(n3) and I\'m lea

9条回答
  •  时光取名叫无心
    2020-12-25 12:23

    Code:

    for (int i=0; i

    Asymptotic Analysis on Big-O:

    Loop A: Time = 1 + 1 + 1 + .. 1 (n times) = n
    
    Loop B+C: Time = 1 + 2 + 3 + .. + m = m(m+1)/2
    
    Time = SUM { m(m+1)/2 | m in (n,0] }
    
    Time < n * (n(n+1)/2) = 1/2 n^2 * (n+1) = 1/2 n^3 + 1/2 n^2
    
    Time ~ O(n^3)
    

提交回复
热议问题