简体   繁体   English

这个算法的时间复杂度是多少? 计算一个字符的唯一性

[英]What is the time complexity of this algorithm? Calculating of uniqueness of a character

How would I compute the time complexity of this algorithm?我将如何计算该算法的时间复杂度? The outer for loop runs n times.外部 for 循环运行 n 次。 The inside for loop runs n-1, n-2, n-3, n-4, ... nn times after each iteration.内部 for 循环在每次迭代后运行 n-1, n-2, n-3, n-4, ... nn 次。

/*
* isUniqueBrute - This algorithm uses the brute force approach by comparing each character 
* in the string with another. Only a single comparison is made per pair of characters.
*/
bool isUniqueBrute(string str)
{
    char buffer;

    for (int i = 0; i < str.length(); i++)
    {
        for (int j = i+1; j < str.length(); j++)
        {
            if (str[i] == str[j])
                return false;
        }
    }

    return true;
}

You perform the calculation by doing the math:您通过进行数学运算来执行计算:

outer loop runs n times: O(n)
inner loop runs n-1, n-2, n-3, ... 0 times.

So you break down the iterations:所以你分解迭代:

1 + 1 + 1 + 1 + ... n times  = outer loop
n-1 + n-2 + n-3 + ... n times = inner loop

Rearranging:重新排列:

1+n-1 = n
1+n-2 = n-1
1+n-3 = n-2
... n times 

Add those up, and you get the sum of all numbers from 1..n.把这些加起来,你就得到了 1..n 中所有数字的总和。 I'm sure you know the formula by now, but:我相信你现在已经知道这个公式了,但是:

n * (n+1) / 2 n * (n+1) / 2

Which, if you expand it, includes as the dominant element.其中,如果你展开它,包括作为主要元素。 So this function is O(n²).所以这个函数是O(n²)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM