【问题标题】:What is the complexity of the code below?下面代码的复杂度是多少?
【发布时间】:2015-07-05 07:23:59
【问题描述】:

谁能帮我找出以下代码的复杂性?

#include<iostream>
#include<string.h>
using namespace std;
//finding the factorial value
int fact(int n)
{
    return (n<=1)?1 : n*fact(n-1);
}

int fun(char *str)
{
    int rank=1;
    int len=strlen(str);

    for (int i=0;str[i]!='\0';i++)
    {    
        int count=0;
        //finding characters smaller than str[i]
        for(int j=i+1;str[j]!='\0';j++)
        {
            if(str[j]<str[i])
            count++;
        }

        len--;
        //finding the rank
        rank+=count*fact(len);
    }
    return rank;
}

int main()
{
    char str[]="string";
    cout<<endl<<fun(str);
    return 0;
}

我认为是 O(n^2)。

【问题讨论】:

    标签: c++ time-complexity


    【解决方案1】:

    阶乘函数是O(n),fun是O(n^2),所以实际上总共是O(n^2)。

    【讨论】:

    • related answer 和 fun 是 O(n^2) ,这从嵌套循环中很明显,在外循环中 fact() 被调用 n 次。所以,最多是 O(n^2 ) 其中 n 是字符串的长度。
    • thnk u zan..你能逐步解释一下它是如何 O(n^2)
    • 首先 main() 只调用 fun() 一次。而 fun() 需要一个大小为 n 的字符串。所以,我们只需要找到 fun() 以 n 表示的时间复杂度在 fun() 内部,我们有两个循环。第一个循环运行 n 次,第二个循环运行 n-1 次。所以,总共 n*(n-1) 是 O(n^2) 但在 fun() 内部,我们称之为 fact () n 次和 fact() 只是 O(2^log2(n)) = O(n)。所以总共应该是 O(n^2)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    相关资源
    最近更新 更多