Leetcode692 Top K Frequent Words
题目描述
example:
1 | Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2 |
1 | Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 |
解决方案:
Step1: 统计词频:
1 | Map<String, Integer> map = new HashMap(); |
Step2: 比较:
1 | List<String> result = new ArrayList<>(); |
Step3: 输出:
1 | return result.subList(0,k); |
最优解:Heap
Step1: 统计词频:
1 | Map<String, Integer> map = new HashMap(); |
Step2: PriorityQueue:
1 | PriorityQueue<String> heap = new PriorityQueue<String>( |
Step3: 从heap提取前k个值,然后倒序输出
1 | for (String word: count.keySet()) { |