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

题目

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;

    }
};

猜你喜欢

转载自blog.csdn.net/tan_change/article/details/80139752