Time complexity of nested for-loop

前端 未结 6 697
花落未央
花落未央 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:19

    First we'll consider loops where the number of iterations of the inner loop is independent of the value of the outer loop's index. For example:

     for (i = 0; i < N; i++) {
         for (j = 0; j < M; j++) {
             sequence of statements
          }
      }
    

    The outer loop executes N times. Every time the outer loop executes, the inner loop executes M times. As a result, the statements in the inner loop execute a total of N * M times. Thus, the total complexity for the two loops is O(N2).

提交回复
热议问题