class Solution {
public:
	vector<int> topKFrequent(vector<int>& nums, int k) {
		vector<int> res;
		unordered_map<int, int> freq;

		// Note that: we need caputre a map by reference,
		// otherwise we can't use the operator[].
		// See also: https://stackoverflow.com/a/6281071
		auto comp_by_map = [&freq](const int& a, const int& b) {
			return freq[a] < freq[b];
		};

		// Note that: here we need pass our lambda /comp_by_map/ to the
		// constructor of std::priority_queue.
		priority_queue<int, vector<int>, decltype(comp_by_map)> pq(comp_by_map);

		for (auto n: nums) {
			freq[n] = freq.find(n) == freq.end() ? 1 : freq[n] + 1;
		}
		for (auto iter: freq) {
			pq.push(iter.first);
		}
		while (k > 0) {
			res.push_back(pq.top());
			pq.pop();
			k--;
		}
		return res;
	}
};