LeetCode 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.
*
*****************************************************************************/
1.分析,首先此题应该用哈希表存储数字,频率
unordered_map

#include <iostream> 
#include <queue> 
    using namespace std;
    int main() {
        priority_queue<int, vector<int>, less<int> >q;//使用priority_queue<int> q1;一样 
        for (int i = 0;i<10;i++)
            q.push(i);
        while (!q.empty()) {
            cout << q.top() << endl;
            q.pop();
        }
        return 0;
    }
// 输出9-0

因此根据上述分析可得

#include <iostream>
#include<queue>
#include<map>
#include <unordered_map>
#include <vector>
#include <set>
using namespace std; 
      vector<int> topKFrequent(vector<int>& nums, int k) {
          vector<int>result;
        //一,统计处频次 
        unordered_map<int, int> mapping;

        for (auto number : nums)          //基于范围内的for循环
            mapping[number]++;
        //二,根据频次压入最大堆中 
        // pair<first, second>: first is frequency, second is number 
        priority_queue<pair<int, int>> pri_que; //最大堆 
        for (auto it = mapping.begin(); it != mapping.end(); it++)
            pri_que.push(make_pair(it->second, it->first));
        //三,获取结果 
        while (result.size() < k) {
            result.push_back(pri_que.top().second);
            pri_que.pop();
        }

      return result;
    }
    //测试
    int main()
    {
        vector<int>nums = { 1,1,1,2,2,3 };
        vector<int>result;
        result = topKFrequent(nums, 2);
        for (auto c : result)
            cout << c << endl;
    }

参考博文http://blog.csdn.net/EbowTang/article/details/51317106

你可能感兴趣的:(LeetCode)