Created
July 10, 2016 17:43
-
-
Save wweic/95cf29c3e0833f1dbf92d5308591fe0b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <unordered_map> | |
#include <queue> | |
using namespace std; | |
class Solution { | |
public: | |
vector<int> topKFrequent(vector<int>& nums, int k) { | |
vector<int> result; | |
unordered_map<int, int> count; | |
for (vector<int>::iterator itr = nums.begin(); itr != nums.end(); ++itr) { | |
++count[*itr]; | |
} | |
priority_queue<pair<int, int>, vector<pair<int, int> >, std::greater<pair<int, int> > > topk; | |
for (unordered_map<int, int>::iterator itr = count.begin(); itr != count.end(); ++itr) { | |
topk.push(make_pair(itr->second, itr->first)); | |
if (topk.size() > k) { | |
topk.pop(); | |
} | |
} | |
while (!topk.empty()) { | |
result.push_back(topk.top().second); | |
topk.pop(); | |
} | |
reverse(result.begin(), result.end()); | |
return result; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment