692. Top K Frequent Words

1.Description(Medium)

Given a list of words and an integer k, return the top k frequent words in the list.

Notice

You should order the words by the frequency of them in the return list, the most frequent one comes first. If two words has the same frequency, the one with lower alphabetical order come first.

Example

Given

[
    "yes", "lint", "code",
    "yes", "code", "baby",
    "you", "baby", "chrome",
    "safari", "lint", "code",
    "body", "lint", "code"
]

for k =3, return["code", "lint", "baby"].

for k =4, return["code", "lint", "baby", "yes"],

Challenge

Do it in O(nlogk) time and O(n) extra space.

Extra points if you can do it in O(n) time with O(k) extra space approximation algorithms.

Tags

Hash Table Heap Priority Queue

2.Code

Version 1: HashMap + PriorityQueue(MinHeap)

遍历数组来统计词频。用一个Word class来表示每个单词和其词频。

用一个HashMap来存每个单词和其Word。

用一个PriorityQueue来对HashMap中Word进行排序,重构Comparator来实现

1)按词频重大到小排序

2)词频相同时,按字典序排序。(String.compareTo())

然后依次取k个queue顶元素。

注意一开始要判断k==0,否则在初始化priorityqueue的时候会报错。

Version 2: Quick Select

https://www.jiuzhang.com/problem/top-k-frequent-words/

最优解法:quick select

  • Time: O(n + klogk)

  • Space: O(n) HashMap

  • HashMap 记录元素的频数

Last updated

Was this helpful?