题解 | 小红书推荐系统
小红书推荐系统
https://www.nowcoder.com/practice/e5b39c9034a84bf2a5e026b2b9b973d0
#include<bits/stdc++.h>
#define int long long
#define s second
#define f first
using namespace std;
const int N = 1e5+10;
const int M = 1e9+7;
void solve()
{
map<string,int> p;
vector<pair<string,int>> q;
string s;
while(cin>>s)
{
p[s] ++;
}
//因为map不能用sort排序,所以把大于3的字符串存入vector<pair<string,int>>类型的p中
for(auto e : p)
{
if(e.second>=3)
{
q.push_back(e);
}
}
//自定义sort排序
sort(q.begin(),q.end(),
[](const pair<string, int>& a, const pair<string, int>& b) {
if (a.second != b.second) {
// 频次不同:频次高的排在前面
return a.second > b.second;
} else {
// 频次相同:按字典序升序排列
return a.first < b.first;
}
}
);
for(auto e : q)cout<<e.first<<endl;
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
int _ = 1;
//cin >> _ ;
while(_--) solve();
return 0;
}
查看8道真题和解析