Time complexity of nested for-loop

前端 未结 6 627
花落未央
花落未央 2020-11-22 08:51

I need to calculate the time complexity of the following code:

for (i = 1; i <= n; i++)
{
  for(j = 1; j <= i; j++)
  {
   // Some code
  }
}
         


        
6条回答
  •  北海茫月
    2020-11-22 09:27

    A quick way to explain this is to visualize it.

    if both i and j are from 0 to N, it's easy to see O(N^2)

    O O O O O O O O
    O O O O O O O O
    O O O O O O O O
    O O O O O O O O
    O O O O O O O O
    O O O O O O O O
    O O O O O O O O
    O O O O O O O O
    

    in this case, it's:

    O
    O O
    O O O
    O O O O
    O O O O O
    O O O O O O
    O O O O O O O
    O O O O O O O O
    

    This comes out to be 1/2 of N^2, which is still O(N^2)

提交回复
热议问题