【问题标题】:Working out the time complexity of this code计算这段代码的时间复杂度
【发布时间】:2021-06-23 01:06:52
【问题描述】:

显示您的步骤的代码的时间复杂度是多少?我试图通过O(T + n + n ^ 2 + n)= O(T + 2 n + 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(T * (n + n^2 + n)) == O(T * n^2)嵌套循环增加了复杂性,所以我们有T * n^2,而不是T + n^2
  • 除了 Dmitry 写的: (1) 由于n 在每次迭代中可以有不同的值,所以写成: O( i=1 到 T 的总和: (n_i)^2)。 (2) 如果我正确理解“O(n^2)”循环,我认为这只是它的最坏情况复杂度,但它的平均情况复杂度(假设 p 的内容是随机的)只有 O(n) .
  • 我已回滚您的最新编辑。您提供的 shorturl 没有指向任何地方。

标签: c++ algorithm performance time-complexity big-o


【解决方案1】:

复杂性算术的经验法则是

  • 添加了后续循环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)

【讨论】:

    猜你喜欢
    • 2019-09-27
    • 1970-01-01
    • 2018-05-28
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    相关资源
    最近更新 更多