Top K Frequent Elements

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

#include 
#include 
#include 
#include 
#include 
using namespace std;

class Solution {
public:
    vector topKFrequent(vector& nums, int k) {
        //element,frequency hash/iter
        unordered_map hash;
        unordered_map::iterator iter;
        for(int i=0;i,vector>,greater> > q;
        for(iter=hash.begin();iter!=hash.end();iter++){
            if(q.size()==k){
                if(iter->second>q.top().first){
                    q.pop();
                    q.push(make_pair(iter->second,iter->first));
                }
            }  else{
                q.push(make_pair(iter->second,iter->first));
            }

        }
        vector res;
        while(! q.empty()){
            res.push_back(q.top().second);
            q.pop();
        }
        return res;

    }
};

int main(){
    int arr[]={1,1,1,2,2,3};
    vector vec(arr,arr+sizeof(arr)/sizeof(int));
    int k=2;

    vector res=Solution().topKFrequent(vec,k);
    for(int i=0;i

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