计算这段代码的时间复杂度

问题描述

我的代码显示您的步骤的时间复杂度是多少?我试图通过做 O(T+n+n^2+n) = O(T+2n+n^2) = O(n^2) 来弄清楚。我说的对吗?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    int T,n,nClone;
    cin >> T;
    while (T--) { //O(T)
        //inputting p[n]
        scanf_s("%d",&n);
        nClone = n;
        int* p = new int[n];
        for (int i = 0; i < n; i++) { //O(n)
            scanf_s("%d",&p[i]);
        }

        vector <int>pDash;

        while (n != 0) { //O(n^2)
            //*itr = largest element in the array
            auto itr = find(p,p + n,*max_element(p,p + n));
            for (int i = distance(p,itr); i < n; i++) {
                pDash.push_back(p[i]);
            }
            
            n = distance(p,itr);
        }
        for (int i = 0; i < nClone; i++) { //O(n)
            printf("%d\n",pDash[i]);
        }
        delete[] p;
    }
    return 0;
}

解决方法

复杂性算术的经验法则是

  • 随后的循环被添加O(loop1) + O(loop2)
  • 嵌套循环相乘O(loop1) * O(loop2)

就你而言:

  while (T--) { // O(T)
    ..
    // nested in "while": O(T) * O(n)
    for (int i = 0; i < n; i++) { // O(n) 
      ...
    }

    // nested in "while": O(T) * O(n)
    while (n != 0) { // O(n) 
      // nested in both "while"s : O(T) * O(n) * O(n)
      for (int i = distance(p,itr); i < n; i++) { // O(n)
        ...
      }
    }

    // nested in "while": O(T) * O(n) 
    for (int i = 0; i < nClone; i++) { // O(n)
      ...
    }
}

我们有:

O(T) * (O(n) + O(n) * O(n) + O(n)) == O(T * n^2)