From a7b808cb39ca9ffd7d73b2379e3d34f957d53203 Mon Sep 17 00:00:00 2001 From: Eatswap Date: Thu, 20 Oct 2022 01:27:33 +0800 Subject: [PATCH] add: 221019 --- cpp/2210/221019.cpp | 45 +++++++++++++++++++++++++++++++++++++++++ cpp/2210/CMakeLists.txt | 2 +- 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 cpp/2210/221019.cpp diff --git a/cpp/2210/221019.cpp b/cpp/2210/221019.cpp new file mode 100644 index 0000000..33fc41b --- /dev/null +++ b/cpp/2210/221019.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +#include +#include + +/** + * 692. Top K Frequent Words + * + * Given an array of strings words and an integer k, return the k most frequent strings. + * Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order. + */ + +class Solution { +public: + static std::vector topKFrequent(const std::vector& words, int k) { + std::unordered_map m; + std::for_each(words.begin(), words.end(), [&](auto&& x) { ++m[x]; }); + + auto cmp = [](auto&& x, auto&& y) { + return (x.second != y.second) ? x.second > y.second : x.first < y.first; + }; + + using PSI = std::pair; + std::priority_queue, decltype(cmp)> q; + std::for_each(m.begin(), m.end(), [&](auto&& x) { + q.push(x); + if (q.size() > k) + q.pop(); + }); + + std::vector ret; + ret.reserve(k); + while (!q.empty()) { + ret.push_back(q.top().first); + q.pop(); + } + + return ret; + } +}; + +int main() { + return 0; +} diff --git a/cpp/2210/CMakeLists.txt b/cpp/2210/CMakeLists.txt index b10edb7..7608e02 100644 --- a/cpp/2210/CMakeLists.txt +++ b/cpp/2210/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2210) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2210 221001.cpp) +ADD_EXECUTABLE(2210 221019.cpp)