leetcode692. 前K个高频单词

typedef pair<string, int> Node;  // 这个Node也是为了排序准备的,没人喜欢瞎费功夫
// debug是为了显示中间结果, 看看有没有出问题, 对核心代码运行没有影响
// 这个函数很重要, 因为我们的排序都是基于这个原则
// 如果两个单词的频率都相同的话, 我们要按照字符顺序进行排序
// 如果频率不相同的话, 直接按频率大小由大到小排序
bool compare2(const Node& node1, const Node& node2) {
	if (node1.second == node2.second)
		return node1.first < node2.first;
	return node1.second > node2.second;
}

class Solution {
public:
	vector<string> topKFrequent(vector<string>& words, int k) {
		// 首先统计词频
		vector<string> ans;
		map<string,int> word_counts;
		for (int i = 0; i < words.size(); i++) {
			word_counts[words[i]]++;
		}
        // 将单词和相应的词频打包成pair,放到nodeVec中, 主要是为了排序, 不然我才懒得倒腾呢
		vector<Node> nodeVec;
		for (const auto& item : word_counts) {
			nodeVec.push_back(Node(item.first, item.second));
		}
#if Debug == 0:
		cout << "Debug Test" << endl;
		for (const auto& item : nodeVec) {
			cout << item.first << "--->" << item.second << endl;
		}
#endif
		// 然后进行排序
		sort(nodeVec.begin(), nodeVec.end(),compare2);
#if Debug == 0:
		for (auto item : nodeVec) {
			cout << item.first << "--->" << item.second << endl;
		}
#endif

		// 最后进行输出
		for (int i = 0; i < k && i < nodeVec.size(); i++) {
			ans.push_back(nodeVec[i].first);
		}
		return ans;
	}
	
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值