LeetCode-347. Top K Frequent Elements

Description

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

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

Solution 1(C++)

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> map;
        for(int num : nums){
            map[num]++;
        }

        vector<int> res;
        // pair<first, second>: first is frequency,  second is number
        priority_queue<pair<int,int>> pq; 
        for(auto it = map.begin(); it != map.end(); it++){
            pq.push(make_pair(it->second, it->first));
            if(pq.size() > (int)map.size() - k){
                res.push_back(pq.top().second);
                pq.pop();
            }
        }
        return res;
    }
};

Solution 2(C++)

class Solution{
public:
    vector<int> topKFrequent(vector<int>& nums, int k){
        unordered_map<int, int> m;
        for(int n: nums) m[n]++;

        vector<vector<int>> buckets(nums.size()+1);
        vector<int> res;
        for(auto it=m.begin(); it!=m.end(); it++){
            buckets[it->second].push_back(it->first);
        }
        for(int i=nums.size(); i>=0&&res.size()<k; i--){
            for(int b:buckets[i]){
                res.push_back(b);
                if(res.size()==k) break;
            }
        }
        return res;
    }
};

算法分析

这道题目不难,主要是要注意题目Note中对算法时间复杂度的要求,所以解法二中使用了桶排序。解法一中使用了优先队列这个数据结构,我还没有系统学习,准备搞一波。

程序分析

注意优先队列这种数据结构。

猜你喜欢

转载自blog.csdn.net/zy2317878/article/details/80596172