找出words中出现频率最多的词

#include 
#include 
#include 
#include 
#include 
using namespace std;

//解法一
string mostFrequent(vector<string>& words) {
	unordered_map<string, int> wordCount;//记录单词和单词出现的次数
	int maxFre = 0;
	for (int i = 0; i < words.size(); i++)
	{
		wordCount[words[i]]++;
		maxFre = max(maxFre, wordCount[words[i]]);//记录最大出现次数
	}
	for (auto& e : wordCount)
	{
		if (e.second == maxFre)//返回最大出现次数的key
		{
			return e.first;
		}
	}
	return "";
}
//解法二
string mostFrequentV2(vector<string>& words) {
	unordered_map<string, int> wordCount;//记录单词和单词出现的次数
	for (int i = 0; i < words.size(); i++)
	{
		wordCount[words[i]]++;
	}
	vector<pair<string, int>> temp(wordCount.begin(), wordCount.end());//复制到vector
	stable_sort(temp.begin(), temp.end(), [](pair<string, int> a, pair<string, int>b) {return a.second > b.second; });//降序排序
	return temp[0].first;
}
int main() {
	vector<string> words;
	words.push_back("Sad");
	words.push_back("Happy");
	words.push_back("Sad");
	words.push_back("Okay");
	words.push_back("Happy");
	words.push_back("Okay");
	words.push_back("Happy");
	words.push_back("Yeah");
	words.push_back("Ahhhhh");
	string answer = mostFrequent(words);
	cout << "The most frequent word is: " << answer << endl;
	return 0;
}
输出:
The most frequent word is: Happy

你可能感兴趣的:(c++,算法,开发语言)