[leetcode] 347. Top K Frequent Elements 解题报告

题目链接:https://leetcode.com/problems/top-k-frequent-elements/

Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

Note: 

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

思路: 用一个hash表计数所有的元素, 然后将其以元素个数为key放入优先队列中去, 然后取出前k个就是了, 涉及到两个比较高级的数据结构, unordered_map, 和priority_queue, 另外优先队列因为是以计数为key, 所有要将元素和其计数以pair的形式入队列, 然后要将计数值为pair的第一个, 元素值为第二个. 之后取出优先队列的前k个数就是了.

代码如下:

class Solution {
public:
    vector topKFrequent(vector& nums, int k) {
        unordered_map hash;
        vector result;
        for(auto val: nums) hash[val]++;
        priority_queue> que;
        for(auto val: hash) que.push(make_pair(val.second, val.first));
        while(k--)
        {
            auto val= que.top();
            result.push_back(val.second);
            que.pop();
        }    
        return result;
    }
};



你可能感兴趣的:(leetcode,hash,优先队列)