【发布时间】:2019-08-14 11:16:49
【问题描述】:
请从 geeksforgeeks 看这个问题的解决方案 2 https://www.geeksforgeeks.org/how-to-sort-a-big-array-with-many-repetitions/ 它使用 stl::map 并说解决方案是 O(n+mlogm),它假设 stl::map 插入和查找在 O(1) 时间内。这是正确的吗?
给定链接中的代码是:
void sort(int arr[], int n)
{
//1. Create an empty hash table.
map<int, int> count;
//2. Input array values are stores as key and their
//counts are stored as value in hash table.
for (int i=0; i<n; i++)
count[arr[i]]++;
map<int, int>::iterator it;
int index = 0;
//3. Consider all keys of hash table and sort them.
//In std::map, keys are already sorted.
//4. Traverse all sorted keys and print every key its value times.
for (it=count.begin(); it!=count.end(); ++it)
{
while(it->second--)
arr[index++]=it->first;
}
}
【问题讨论】:
-
习惯上将代码放入问题本身。它为我们节省了点击次数,如果链接失效,您的问题将来也不会变得毫无用处。
-
用我说的代码更新了问题
标签: c++ dictionary stl time-complexity unordered-map