如何使用min heap来解决这个问题

时间:2016-05-02 15:19:34

标签: c++ algorithm min-heap

我想知道如何使用min heap来解决以下问题。

我想解决的是使用哈希表并保存数字的计数。但我不知道如何使用min heap来解决这个问题。

给定一个非空的整数数组,返回k个最常见的元素。

例如, 给定[1,1,1,2,2,3]和k = 2,返回[1,2]。

注意: 您可以假设k始终有效,1≤k≤唯一元素的数量。 算法的时间复杂度必须优于O(n log n),其中n是数组的大小。

vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> counts;
        priority_queue<int, vector<int>, greater<int>> max_k;
        for(auto i : nums) ++counts[i];
        for(auto & i : counts) {
            max_k.push(i.second);
            // Size of the min heap is maintained at equal to or below k
            while(max_k.size() > k) max_k.pop();
        }
        vector<int> res;
        for(auto & i : counts) {
            if(i.second >= max_k.top()) res.push_back(i.first);
        }
        return res;
    }

1 个答案:

答案 0 :(得分:2)

代码的工作原理如下:

for(auto i : nums) ++counts[i];  // Use a map to count how many times the
                                 // individual number is present in input

priority_queue<int, vector<int>, greater<int>> max_k;  // Use a priority_queue
                                                       // which have the smallest
                                                       // number at top

for(auto & i : counts) {
    max_k.push(i.second);                 // Put the number of times each number occurred
                                          // into the priority_queue

    while(max_k.size() > k) max_k.pop();  // If the queue contains more than
                                          // k elements remove the smallest
                                          // value. This is done because
                                          // you only need to track the k
                                          // most frequent numbers

vector<int> res;                                         // Find the input numbers
for(auto & i : counts) {                                 // which is among the most
    if(i.second >= max_k.top()) res.push_back(i.first);  // frequent numbers
                                                         // by comparing their
                                                         // count to the lowest of
                                                         // the k most frequent.
                                                         // Return numbers whose 
                                                         // frequencies are among
                                                         // the top k
  

修改

正如@SergeyTachenov How min heap is used here to solve this所指出的,你的结果向量可能会返回多于k个元素。也许你可以通过这样做来解决这个问题:

for(auto & i : counts) {
    if(i.second >= max_k.top()) res.push_back(i.first);
    if (res.size() == k) break; // Stop when k numbers are found
}

另一个小评论

你真的不需要while - 声明:

while(max_k.size() > k) max_k.pop();

if - 声明可以。

相关问题