347. 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.

Analysis:
1. 注意这里主要使用map/multimap关联容器,它是根据元素(key, value>的key值有序排列的,可以选择不同的排序方式,默认使用less(Pred>模板函数从小到大排列。
2. 还有一点注意map/multimap只能使用双向迭代器,不支持‘<’’>’号等。
3. 代码中有注释,还是要熟悉模板标准模板库STL

Source Code(C++):

#include <iostream>
#include <vector>
#include <map>
using namespace std;

class Solution {
public:
    vector<int> topKFrequent(const vector<int>& nums, const int k) {
         //使用map存储,<元素,出现次数>,map中‘出现次数’自动按‘元素’从小到大排列,这里的存储次序对我们没什么用
        map<int, int> mp1; 
        for(int i=0; i<nums.size(); i++) {
            if (mp1.find(nums.at(i)) == mp1.end()) {
                mp1[nums.at(i)] = 1;
            }
            else {
                mp1[nums.at(i)]++;
            }
        }
        //在multimap中存储,<出现次数,元素>,multimap中使用greater<int>模板函数使‘元素’按‘出现次数’从大到小排列
        multimap<int, int, greater<int>> mp2;   
        for (map<int, int>::iterator i=mp1.begin(); i!=mp1.end(); i++){
            mp2.insert(multimap<int, int>::value_type(i->second, i->first));
        }

        //取出multimap中前k个pair中对应的‘元素’
        vector<int> res;
        multimap<int, int, greater<int>>::iterator mi=mp2.begin();
        for (int i=0; i<k; i++)
        {
            res.push_back(mi->second);
            mi++;
        }
        return res;
    }
};

int main() {
    vector<int> v;
    v.push_back(5);v.push_back(1);v.push_back(1);v.push_back(1);v.push_back(3);v.push_back(3);v.push_back(10);v.push_back(10);
    Solution sol;
    vector<int> v2;
    v2 = sol.topKFrequent(v, 2);
    return 0;
}

你可能感兴趣的:(347. Top K Frequent Elements)