692.Top-K-Frequent-Words
692. Top K Frequent Words
题目地址
https://leetcode.com/problems/top-k-frequent-words/
题目描述
代码
Approach #1: Sorting
Intuition and Algorithm
Count the frequency of each word, and sort the words with a custom ordering relation that uses these frequencies. Then take the best k
of them.
Complexity Analysis
Time Complexity: O(_NlogN), where N is the length of
words
. We count the frequency of each word in O(_N) time, then we sort the given words in O_(_NlogN) time.Space Complexity: O_(_N), the space used to store our
candidates
.
Approach #2 Heap
Intuition and Algorithm
Count the frequency of each word, then add it to heap that stores the best k
candidates. Here, "best" is defined with our custom ordering relation, which puts the worst candidates at the top of the heap. At the end, we pop off the heap up to k
times and reverse the result so that the best candidates are first.
Last updated