https://leetcode.com/problems/top-k-frequent-words/

Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
    Note that "i" comes before "love" due to a lower alphabetical order.

개수가 많은게 앞에 와야하면서도, 알파벳의 순서까지도 따졌다. 흠...

unordered_map으로 개수를 저장해 주었다.

그리고 heap (priority_queue)를 통해서 우선순위를 정해주었다.

람다함수를 통해서.. 약간의 수정을 거쳐서 priority_queue를 사용했다.

https://en.cppreference.com/w/cpp/container/priority_queue

class Solution {
public:
	vector<string> topKFrequent(vector<string>& words, int k) {
		std::unordered_map<string, int> u_map;
		auto cmp = [](pair<int, string> left, pair<int, string> right) {
			if (left.first == right.first)
			{
				return left.second > right.second;
			}
			else
				return left.first < right.first;
		};
		std::priority_queue<pair<int, string>, std::vector<pair<int, string>>, decltype(cmp)> p_queue(cmp);
		for (int i = 0; i < words.size(); ++i)
		{
			if (u_map.find(words[i]) != u_map.end())
			{
				u_map[words[i]]++;
			}
			else
			{
				u_map[words[i]] = 1;
			}
		}

		for (auto itr = u_map.begin(); itr != u_map.end(); ++itr)
		{
			p_queue.emplace(make_pair(itr->second, itr->first));
		}
		vector<string> result(k);
		for (int i = 0; i < k; ++i)
		{
			result[i] = p_queue.top().second;
			p_queue.pop();
		}
		return result;
	}
};

Runtime: 12 ms, faster than 91.12% of C++ online submissions for Top K Frequent Words.

Memory Usage: 12.7 MB, less than 73.00% of C++ online submissions for Top K Frequent Words.

Runtime: 4 ms, faster than 100.00% of C++ online submissions for Top K Frequent Words.

Memory Usage: 12.5 MB, less than 90.85% of C++ online submissions for Top K Frequent Words.