Jon*_*Mee 10 c++ sorting duplicates time-complexity bucket-sort
这个评论表明我的O(n log n)解决方案有一个O(n)替代方案来解决这个问题:
鉴于string str("helloWorld")预期的产出是:
l = 3
o = 2
我的解决方案是这样做:
sort(begin(str), end(str));
for(auto start = adjacent_find(cbegin(str), cend(str)), finish = upper_bound(start, cend(str), *start); start != cend(str); start = adjacent_find(finish, cend(str)), finish = upper_bound(start, cend(str), *start)) {
cout << *start << " = " << distance(start, finish) << endl;
}
Run Code Online (Sandbox Code Playgroud)
这显然受到排序的限制str.我认为这需要一个桶排序解决方案?有什么比我更缺的聪明吗?
Bat*_*eba 13
这是一种方式,即O(N),代价是为每个可能的char值维护存储.
#include <string>
#include <limits.h> // for CHAR_MIN and CHAR_MAX. Old habits die hard.
int main()
{
std::string s("Hello World");
int storage[CHAR_MAX - CHAR_MIN + 1] = {};
for (auto c : s){
++storage[c - CHAR_MIN];
}
for (int c = CHAR_MIN; c <= CHAR_MAX; ++c){
if (storage[c - CHAR_MIN] > 1){
std::cout << (char)c << " " << storage[c - CHAR_MIN] << "\n";
}
}
}
Run Code Online (Sandbox Code Playgroud)
这种便携式解决方案很复杂,因为它char可以是signed或者unsigned.
| 归档时间: |
|
| 查看次数: |
651 次 |
| 最近记录: |