题目地址
LeetCode#692 Top K Frequent Words
题目描述
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 | Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2 |
Example 2:
1 | Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 |
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Input words contain only lowercase letters.
Follow up:
- Try to solve it in O(n log k) time and O(n) extra space.
解题思路
经典题型,使用字典保存字符串与次数键值对,然后使用有序序列统计即可。
解题代码
1 | class Solution { |