[英]What's the complexity of this algorithm?
這是一種計算另一個字符串(文本)中一個字符串(search_word)的字謎出現的算法:
#include<iostream>
#include<algorithm>
#include<string>
#include<deque>
using namespace std;
int main()
{
string text = "forxxorfxdofr";
string search_word = "for";
deque<char> word;
word.insert(word.begin(), text.begin(), text.begin() + search_word.size());
int ana_cnt = 0;
for (int ix = 3; ix <= text.size(); ++ix)
{
deque<char> temp = word;
sort(word.begin(), word.end());
if (string(word.begin(), word.end()) == search_word)
++ana_cnt;
word = temp;
word.pop_front();
word.push_back(text[ix]);
}
cout << ana_cnt << endl;
}
這個算法的復雜度是多少?
我認為這是O(n)
算法,其中n
是文本的長度。 這是因為執行for循環內的內容所需的時間量與n
的長度無關。 但是,有人認為這不是O(n)
。 他們說,排序算法在計算復雜度時也很重要。
如果僅考慮長度為n
的字符串text
作為輸入,則為O(n)
。
證明:您正在將ix
從3
循環(可能是search_word.size()
,不是嗎?)到text.size()
,因此您會漸進地執行循環主體n
次(因為沒有break
, continue
或修改) ix
在循環體內)。
循環體獨立於n
。 它對固定大小的隊列進行排序,即m
= search_word.size()
,在一般情況下(最壞情況O(m^2)
)為O(m log(m))
O(m^2)
)。 因為這與n
無關,所以我們總共使用O(n)
。
它不是O(n)
:如果您想更精確一點,您可能會計算長度為m
search_word
作為輸入,這search_word
O(nm log(m))
, O(nm^2)
在最壞的情況下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.