简体   繁体   中英

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. The inside for loop runs n-1, n-2, n-3, n-4, ... nn times after each iteration.

/*
* 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. I'm sure you know the formula by now, but:

n * (n+1) / 2

Which, if you expand it, includes as the dominant element. So this function is O(n²).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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