簡體   English   中英

這個算法的時間復雜度是多少? 計算一個字符的唯一性

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

我將如何計算該算法的時間復雜度? 外部 for 循環運行 n 次。 內部 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;
}

您通過進行數學運算來執行計算:

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²)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM