What is time complexity for the following code?

后端 未结 5 1087
刺人心
刺人心 2021-01-17 06:33

It seems the complexity of the following code should be O(n^2) but it\'s O(n), how?

void fun(int n, int arr[])
{
    int i = 0, j = 0;
    for(; i < n; ++         


        
5条回答
  •  失恋的感觉
    2021-01-17 07:21

    j is not reset to 0 with every iteration of the outer loop. As such, it runs to n-1 just once, same as i does. So you have two parallel/intermingled iterations from 0 to (at most) n-1.


    In every step, the program increases i by one. The program terminates when i reaches n. The "outer loop" is run n times.

    There is also an "inner loop" about j. But all it does is increase j until it reaches i (at most, sometimes it does less). j is never decreased. So that part is also run at most n times in total (not n times for each iteration of the "outer loop").

提交回复
热议问题