![](/img/trans.png)
[英]What is the Time Complexity, Space complexity and Algorithm for strstr() function in C++?
[英]What is the Time and space complexity of sort() in C++ with custom comparator function?
考慮以下代碼 -
bool cmp(pair<string,int> &a, pair<string,int> &b) {
return ((a.second > b.second) || (a.second==b.second && a.first<b.first));
}
vector<pair<string,int>> v;
sort(v.begin(),v.end(),cmp);
對於這種情況,我的復雜性是多少? 會是O(nlogn)
嗎?
std::sort
具有時間復雜度: O(NlogN) custom comparisons 。
但在您的情況下,比較器 function cmp
也執行字符串比較,
(a.second==b.second && a.first<b.first)
std::basic_string operator<
具有與字符串大小成線性關系的時間復雜度。
因此,最壞情況的復雜度是O(K*NlogN) 字符比較,其中 K 是字符串的長度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.