题目
Given a non-empty list of words, return the k most frequent elements.
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.
Example 1:1
2
3
4Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
1 | Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 |
解析
经典的问题,寻找topk频率的单词,如果遇到tie则比较字典序,字典序小的在前面,遍历一边统计顺序,利用heap或者说priority queue保存即可,不过记录这道题的目的是用下java 对函数编程的支持,因为以前都是新建一个class做的,比较笨拙
1 | public List<String> topKFrequent(String[] words, int k) { |
总结
topk这种高频入门必刷题,需要熟练掌握,用一些函数式编程的小trick可以让我们做题速度更快,代码更加优雅