使用 stl::map 和 stl::unordered_map 对包含大量重复元素的数组数据进行排序

Use of stl::map and stl::unordered_map for sorting the array data which contains a lot of repeated elements

本文关键字:map stl 数组 元素 数据 排序 unordered 使用 包含大      更新时间:2023-10-16

请看这个问题的解决方案2https://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; 
    } 
} 

这只是 std::unordered_map 的一个错别字,其运算平均O(1(。