由於內部有兩個嵌套的重複循環,remove_dup函數的運行時複雜度爲O(n^2)。我的任務是獲得與O(n)相同的結果。
我真的不知道如何可能看起來像。使運行時複雜度更短(C++)
int add_without_dup (char x, vector<char>& r)
{// pre-condition:
assert (true) ;
// post-condition: x is added to the end of r if it is not yet present in r
// the result is the number of comparisons performed in this function
int i = 0 ;
while (i < size(r) && r[i] != x)
i++ ;
if (i == size(r))
r.push_back (x) ;
return i ;
}
int remove_dup (vector<char>& source, vector<char>& dest)
{// pre-condition:
assert (size (dest) == 0) ;
// post-condition: dest is a copy of source without duplicate elements
// the result is the number of comparisons performed in this function
int nr_of_comparisons = 0 ;
for (int i = 0 ; i < size (source) ; i++)
nr_of_comparisons += add_without_dup (source[i], dest) ;
return nr_of_comparisons ;
}
如果可能的話,首先排序內容。更好的是,查看'std :: set'。 –
將有一個看看,謝謝。 – Julius
@JerryCoffin:如果你開始對序列進行排序,我不確定你將如何到達O(n)算法。這就是說,我不太清楚O(n)算法是用於刪除重複的。 –