Skip to main content

Posts

Showing posts from June, 2022

Priority_queue - Question 5

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. Constraints: 1 <= words.length <= 500 1 <= words[i] <= 10 words[i] consists of lowercase English letters. k is in the range [1, The number of unique words[i]] Analysis: This question is quite straightforward. We can use a priority_queue to keep the top K valid elements. One difficulty may be about the comparator of the priority_queue.  In C++, the default order of the priority_queue is with the largest one on the top. But in this question, we need choose the top K with the largest count, so we need a reversed priority_queue. And more, for the same count, we need to choose the one with the lexicographical order. So we need to take care of this in the comparator. See the code below: class Solution { public: typedef pair<int,