{"id":661,"date":"2017-10-21T17:51:38","date_gmt":"2017-10-22T00:51:38","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=661"},"modified":"2018-04-19T08:33:58","modified_gmt":"2018-04-19T15:33:58","slug":"leetcode-692-top-k-frequent-words","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/heap\/leetcode-692-top-k-frequent-words\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 692. Top K Frequent Words"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 692. Top K Frequent Words - \u5237\u9898\u627e\u5de5\u4f5c EP94\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/POERw4yDVBw?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p><strong>Problem:<\/strong><\/p>\n<p>Given a non-empty list of words, return the\u00a0<i>k<\/i>\u00a0most frequent elements.<\/p>\n<p>Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.<\/p>\n<p><b>Example 1:<\/b><\/p>\n<pre class=\"\">Input: [\"i\", \"love\", \"leetcode\", \"i\", \"love\", \"coding\"], k = 2\r\nOutput: [\"i\", \"love\"]\r\nExplanation: \"i\" and \"love\" are the two most frequent words.\r\n    Note that \"i\" comes before \"love\" due to a lower alphabetical order.\r\n<\/pre>\n<p><b>Example 2:<\/b><\/p>\n<pre class=\"\">Input: [\"the\", \"day\", \"is\", \"sunny\", \"the\", \"the\", \"the\", \"sunny\", \"is\", \"is\"], k = 4\r\nOutput: [\"the\", \"is\", \"sunny\", \"day\"]\r\nExplanation: \"the\", \"is\", \"sunny\" and \"day\" are the four most frequent words,\r\n    with the number of occurrence being 4, 3, 2 and 1 respectively.\r\n<\/pre>\n<p><b>Note:<\/b><\/p>\n<ol>\n<li>You may assume\u00a0<i>k<\/i>\u00a0is always valid, 1 \u2264\u00a0<i>k<\/i>\u00a0\u2264 number of unique elements.<\/li>\n<li>Input words contain only lowercase letters.<\/li>\n<\/ol>\n<p><b>Follow up:<\/b><\/p>\n<ol>\n<li>Try to solve it in\u00a0<i>O<\/i>(<i>n<\/i>\u00a0log\u00a0<i>k<\/i>) time and\u00a0<i>O<\/i>(<i>n<\/i>) extra space.<\/li>\n<\/ol>\n<p><script async src=\"\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js\"><\/script><br \/>\n<ins class=\"adsbygoogle\" style=\"display: block; text-align: center;\" data-ad-layout=\"in-article\" data-ad-format=\"fluid\" data-ad-client=\"ca-pub-2404451723245401\" data-ad-slot=\"7983117522\"><\/ins><br \/>\n<script>\n     (adsbygoogle = window.adsbygoogle || []).push({});\n<\/script><\/p>\n<p><strong>Idea:<\/strong><\/p>\n<p>Priority queue \/ min heap<\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/10\/692-ep94.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-666\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/10\/692-ep94.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/10\/692-ep94.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/10\/692-ep94-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/10\/692-ep94-768x432.png 768w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/10\/692-ep94-624x351.png 624w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<p><strong>Solution<\/strong><\/p>\n<p>C++ \/ priority_queue O(n log k) \/ O(n)<\/p>\n<pre class=\"lang:c++ decode:true \">\/\/ Author: Huahua\r\n\/\/ Runtime: 13 ms (&lt; 90.31 %)\r\nclass Solution {\r\nprivate:\r\n    typedef pair&lt;string, int&gt; Node;\r\n    typedef function&lt;bool(const Node&amp;, const Node&amp;)&gt; Compare;\r\npublic:\r\n    vector&lt;string&gt; topKFrequent(vector&lt;string&gt;&amp; words, int k) {\r\n        unordered_map&lt;string, int&gt; count;\r\n        for (const string&amp; word : words)\r\n            ++count[word];\r\n        \r\n        Compare comparator = [](const Node&amp; a, const Node&amp; b) {\r\n            \/\/ order by alphabet ASC\r\n            if (a.second == b.second) \r\n                return  a.first &lt; b.first;\r\n            \/\/ order by freq DESC\r\n            return a.second &gt; b.second;\r\n        };\r\n        \r\n        \/\/ Min heap by frequency\r\n        priority_queue&lt;Node, vector&lt;Node&gt;, Compare&gt; q(comparator);\r\n        \r\n        \/\/ O(n*logk)\r\n        for (const auto&amp; kv : count) {\r\n            q.push(kv);\r\n            if (q.size() &gt; k) q.pop();\r\n        }\r\n        \r\n        vector&lt;string&gt; ans;\r\n        \r\n        while (!q.empty()) {\r\n            ans.push_back(q.top().first);\r\n            q.pop();\r\n        }\r\n        \r\n        std::reverse(ans.begin(), ans.end());\r\n        return ans;\r\n    }\r\n};<\/pre>\n<p><strong>Related Problems<\/strong><\/p>\n<ul>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/hashtable\/leetcode-347-top-k-frequent-elements\/\">[\u89e3\u9898\u62a5\u544a] LeetCode 347. Top K Frequent Elements<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Problem: Given a non-empty list of words, return the\u00a0k\u00a0most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[71,164],"tags":[24,73,72],"class_list":["post-661","post","type-post","status-publish","format-standard","hentry","category-heap","category-medium","tag-frequency","tag-heap","tag-priority-queue","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/661","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=661"}],"version-history":[{"count":7,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/661\/revisions"}],"predecessor-version":[{"id":2608,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/661\/revisions\/2608"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=661"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=661"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=661"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}