3. Top K Frequent Elements

Link to the problem

Description

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

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.

Example

Input: [1,1,1,2,2,3], k = 2, Output: [1,2].
1 is most frequent, 2 is the second frequent element.

Idea

First construct a counter of the elements, then put the elements in an array indexed by the count. Finally, read the array from right to left.

Solution

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        int n = nums.size();
        unordered_map<int, int> counter;
        vector<vector<int> > counts(n + 1);
        vector<int> rtn;
        for (auto it = nums.begin(); it != nums.end(); it++) {
            int key = *it;
            if (counter.find(key) == counter.end()) counter[key] = 1;
            else counter[key]++;
        }
        for (auto it = counter.begin(); it != counter.end(); it++) {
            int element = it->first, count = it->second;
            counts[count].push_back(element);
        }
        int index = n;
        while (rtn.size() < k) {
            for (auto it = counts[index].begin(); it != counts[index].end(); it++) {
                if (rtn.size() == k) return rtn;
                rtn.push_back(*it);
            }
            index--;
        }
        return rtn;
    }
};

Performance

20 / 20 test cases passed.
Runtime: 19 ms

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,939评论 0 23
  • 现在十一点半,想睡,却睡不着! 写点东西我想可能会早点入眠! 刚刚还听到隔壁三个七万一个三条,现在安静多了! 我不...
    张洋很张扬阅读 201评论 0 0
  • 你来自草根 我本就是小小的草 你有北国的记忆 我是来自南方的鸟 我们不该有交集的 但命运就这样 就这样 把咱搅成了...
    本无痕阅读 410评论 9 11
  • 讲课声音大好,还是声音小好? 昨天写“停顿”这个技巧的时候,我就在想停顿是声音的节奏,那讲课时是培训声音越大...
    笑笑1068阅读 662评论 3 1
  • 已经冬天了。 南方冬天的天气湿冷,透到骨头里的那种冷,树的叶跟着风飘下,冷。 有很多话想说,跟从前一样。 发现无论...
    你看到我的小兔了吗阅读 224评论 0 3