【问题标题】:Use of stl::map and stl::unordered_map for sorting the array data which contains a lot of repeated elements使用 stl::map 和 stl::unordered_map 对包含大量重复元素的数组数据进行排序
【发布时间】: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


【解决方案1】:

这只是std::unordered_map 的一个错字,其操作平均 O(1)。

【讨论】:

  • 但是,如果我们使用 unordered_map ,那么这个地图中的元素将不会被排序,因此不会在代码前面假设的 O(1) 时间内。我想知道,是否真的有可能在 O(1) 中使用任何数据结构做到这一点。
  • @RahulAssassin:它说(比较)对(唯一)键进行排序作为步骤之一。
猜你喜欢
  • 2018-10-10
  • 2016-04-27
  • 1970-01-01
  • 2017-03-31
  • 2019-05-30
  • 1970-01-01
  • 2011-06-14
  • 2020-12-08
  • 2020-06-05
相关资源
最近更新 更多