347. Top K Frequent Elements【leetcode解题报告】

11 篇文章 0 订阅
11 篇文章 0 订阅
题目

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.

复杂度分析

优先队列->构造最大堆:O(nlgn)
std::map 按照key排序:STL中的map是红黑树(待学习)

19 ms submission
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        //思路其实蛮简单的,就是按出现的频次排一个顺序;
        unordered_map<int, int> m;
        //自动按照pair[0]进行最大优先队列构造
        priority_queue<pair<int, int>> q;
        vector<int> res;
        for (auto a : nums) ++m[a];
        for (auto it : m) q.push({it.second, it.first});
        for (int i = 0; i < k; ++i) {
            res.push_back(q.top().second); q.pop();
        }
        return res;
     }
}
自己的29ms 找差距
class Solution {
public:
    /*
    1. 数组已经排好序么?
    2. 数组中数字的范围已知么? 遍历map进行k-v存储
    3. 输出的数组需要按频率排序么?
    */
    vector<int> topKFrequent(vector<int>& nums, int k) {
        int len = nums.size();
        map<int,int> fmap;
        for(int i=0;i<len;++i){
            if(fmap.find(nums[i])==fmap.end()){
                fmap[nums[i]] = 0;
            }else{
                fmap[nums[i]]++;
            }
        }

        map<int,vector<int>> bucket;
        for(auto it=fmap.begin();it!=fmap.end();++it){
            bucket[it->second].push_back(it->first);
        }

        vector<int> res;
        //map会自动根据key值进行排序,所以根据迭代器从后往前找topk就可以。
        //用rbegin和rend进行倒序输入
        for(auto it=bucket.rbegin();k>0 && it!=bucket.rend();++it){
            vector<int> temp = it->second;
            while(k>=0 && !temp.empty()){
                res.push_back(temp.back());
                temp.pop_back();
                --k;
            }
        }

        return res;

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值