题目链接:https://leetcode.com/problems/top-k-frequent-words/description/
static const auto __________ = []()
{
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return nullptr;
}();
template<class _Ty1, class _Ty2>
struct MyPairLess {
typedef _Ty1 first_argument_type;
typedef _Ty2 second_argument_type;
typedef bool result_type;
constexpr bool operator() (const pair<_Ty1, _Ty2>& lhs, const pair<_Ty1, _Ty2>& rhs) const {
return lhs.first < rhs.first ||
(!(rhs.first < lhs.first) && lhs.second > rhs.second);
}
};
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
std::unordered_map<std::string, int> hash;
for (auto const& s : words)
hash[s]++;
std::vector<std::pair<int, std::string> > data(words.size());
auto _it = data.begin();
for (auto it = hash.begin(); it != hash.end(); ++it, ++_it)
*_it = std::make_pair(std::move(it->second), std::move(it->first));
std::priority_queue <std::pair<int, std::string>,
std::vector<std::pair<int, std::string>>,
MyPairLess<int, std::string> >
pq{ MyPairLess<int, std::string>(), std::move(data) };
std::vector<string> result(k);
for (auto& it : result)
{
it = std::move(pq.top().second);
pq.pop();
}
return result;
}
};