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

Algorithm 这个算法的时间复杂度是多少?字符唯一性的计算,algorithm,Algorithm,如何计算此算法的时间复杂度?外部for循环运行n次。内部for循环运行n-1、n-2、n-3、n-4。。。每次迭代后n-n次 /* * 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. */ bo

如何计算此算法的时间复杂度?外部for循环运行n次。内部for循环运行n-1、n-2、n-3、n-4。。。每次迭代后n-n次

/*
* 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;
}
/*
*isUniqueBrute-此算法通过比较每个角色使用蛮力方法
*和另一个人在一起。每对字符只进行一次比较。
*/
bool isUniqueBrute(字符串str)
{
字符缓冲区;
对于(int i=0;i
您可以通过以下数学运算来执行计算:

outer loop runs n times: O(n)
inner loop runs n-1, n-2, n-3, ... 0 times.
因此,您将分解迭代:

1 + 1 + 1 + 1 + ... n times  = outer loop
n-1 + n-2 + n-3 + ... n times = inner loop
重新安排:

1+n-1 = n
1+n-2 = n-1
1+n-3 = n-2
... n times 
把这些加起来,你就得到1..n中所有数字的总和。我相信你现在已经知道这个公式了,但是:

n*(n+1)/2

如果你扩展它,它包括作为主导元素。所以这个函数是O(n²)。

请参见此处的可能重复项