leetCode692:前K个高频单词,字典树迷惑题

目录

一、题目描述

二、解题思路

三、代码实现


一、题目描述

给一非空的单词列表,返回前 k 个出现次数最多的单词。

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

示例 1:

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

示例 2:

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

注意:

  • 假定 k 总为有效值, 1 ≤ k ≤ 集合元素数。
  • 输入的单词均由小写字母组成。
     

扩展练习:

  1. 尝试以 O(n log k) 时间复杂度和 O(n) 空间复杂度解决。

二、解题思路

这道题的标签是字典树,可以做,但是没有必要。没有必要的原因在于寻找前K个的单词的操作,字典树并不擅长。只能把字典树遍历一遍然后使用另外的结构统计次数的排序。

那为什么不直接使用其他的结构来做呢,标准库完全可以在同等时间和空间开销内达到要求。

所以这是一道标准可的应用题,搞简单点呗。

  1. 使用哈希表统计所有单词的出现次数;
  2. 将哈希表的内容放进数组里;
  3. 数组自定义排序,然后输出前k个单词即可。

三、代码实现

/*!
 * \file main.cpp
 *
 * \author 90826
 * \date 一月 2021
 *
 * 力扣692:前K个高频单词
 * 标签是字典树,但是没有必要,并没有多便利
 * 还不如使用哈希表+自定义排序(STD应用题)
 */
#include<bits/stdc++.h>
using namespace std;

static bool cmp(pair<string, int>& a, pair<string, int>& b) {
	return a.second != b.second ? a.second > b.second: a.first < b.first ;
}
vector<string> topKFrequent(vector<string>& words, int k) {
	int n = words.size();
	unordered_map<string, int> strMap;
	for (auto &x : words) {
		strMap[x]++;
	}
	vector<pair<string, int>> strVec;
	for (auto ite = strMap.begin(); ite != strMap.end(); ite++) {
		strVec.push_back({ite->first, ite->second});
	}
	sort(strVec.begin(), strVec.end(), cmp);
	vector<string> res;
	for (int i = 0; i < k; i++) {
		res.push_back(strVec[i].first);
	}
	return res;
}
int main() {
	vector<string> words = { "i", "love", "leetcode", "i", "love", "coding" };
	int k = 2;
	words = topKFrequent(words, k);
	for (auto &x : words) {
		cout << x << " ";
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值