题目:

给定一个单词列表 words 和一个整数 k ,返回前 k 个出现次数最多的单词。

返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率, 按字典顺序 排序。

示例 1:

1
2
3
4
输入: words = ["i", "love", "leetcode", "i", "love", "coding"], k = 2
输出: ["i", "love"]
解析: "i""love" 为出现次数最多的两个单词,均为2次。
注意,按字母顺序 "i""love" 之前。

示例 2:

1
2
3
4
输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
输出: ["the", "is", "sunny", "day"]
解析: "the", "is", "sunny""day" 是出现次数最多的四个单词,
出现次数依次为 4, 3, 21 次。

注意:

1 <= words.length <= 500
1 <= words[i] <= 10
words[i] 由小写英文字母组成。
k 的取值范围是 [1, 不同 words[i] 的数量]

解题思路:

这题就是简单的排序,我认为它配不上medium(虽然开始写错了,没有认真读题)

首先我们创建一个哈希表用来存储每个字符串出现的次数

然后我们进行自定义排序即可。

代码:

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
def f(a, b):
if cnt[a] == cnt[b]:
# 字典序小的排前面
if a < b:
return -1
# 大的排后面
else:
return 1
elif cnt[a] < cnt[b]:
return 1
else:
return -1

cnt = defaultdict(int)
heap = []
for x in words: cnt[x] += 1
for key, val in cnt.items(): heap.append(key)

heap = sorted(heap, key=cmp_to_key(f))
return heap[:k]

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> cnt;
vector<string> ans;

// 哈希表
for (auto s: words) ++cnt[s];
// 添加字符串
for (auto [key, val]: cnt) ans.emplace_back(key);
// 排序
sort(ans.begin(), ans.end(), [&](const string &a, const string &b)->bool{
return cnt[a] == cnt[b] ? a < b: cnt[a] > cnt[b];
});
// 删除多余的字符串
ans.erase(ans.begin() + k, ans.end());
return ans;
}
};