題目:給一非空的單詞列表,返回前 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、用map得到出現次數(map有key和value)
2、將得到的次數表複製到multiset中(multiset只有值)
3、仿函數定義比較規則
代碼:
#include<iostream>
#include<map>
#include<set>
#include<string>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;
class Solution
{
public:
class Compare
{
public:
bool operator()(const pair<string, int>& p1, const pair<string, int>& p2)
{
return p1.second > p2.second ||
p1.second == p2.second && p1.first < p2.first;
}
};
vector<string> topKFrequent(vector<string>&words, int k)
{
vector<string> vs(k);
map<string, int> msi;
for (auto & i: words)
{
msi[i]++;//記錄出現次數
}
#if 0
multiset<pair<string, int>, Compare> msp(msi.begin(), msi.end());
int i;
multiset<pair<string, int>, Compare>::iterator mspi = msp.begin();
for ( i = 0; i < k; i++)
{
vs[i] = mspi->first;
mspi++;
}
#else
vector<pair<string, int>> vps(msi.begin(), msi.end());
Compare cp;
sort(vps.begin(), vps.end(), cp);
int i;
for ( i = 0; i < k; i++)
{
vs[i] = vps[i].first;
}
#endif
return vs;
}
};
int main()
{
Solution s;
vector<string> vs{ "the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is" };
vs = s.topKFrequent(vs, 4);
for (auto & i : vs)
{
cout << i << endl;
}
system("pause");
return 0;
}