LeetCode6126:Set自定义排序规则方法
题目#
算法思路#
- 利用map存储信息,方便快速查找到对应食物的信息
- set中存储的为每种烹饪方法,对应的食物和分数
- 为了方便查找到分数最大并且字典序最小的食物,可以利用set自定义排序规则
代码一#
struct Symbol
{
public :
int first;
string second;
bool operator< (const Symbol& r) const
{
if(first!=r.first)return first<r.first;
return second>r.second;
}
};
class FoodRatings {
public:
unordered_map<string,Symbol> fc;
unordered_map<string,set<Symbol>> cs;
FoodRatings(vector<string>& foods, vector<string>& cuisines, vector<int>& ratings) {
for(int i=0;i<foods.size();i++){
fc[foods[i]]= {ratings[i],cuisines[i]};
cs[cuisines[i]].insert({ratings[i],foods[i]});
}
}
void changeRating(string food, int newRating) {
auto & p = fc[food];
cs[p.second].erase({p.first,food});
p.first=newRating;
cs[p.second].insert({newRating,food});
}
string highestRated(string cuisine) {
auto i = cs[cuisine].rbegin();
return i->second;
// return "";
}
};
/**
* Your FoodRatings object will be instantiated and called as such:
* FoodRatings* obj = new FoodRatings(foods, cuisines, ratings);
* obj->changeRating(food,newRating);
* string param_2 = obj->highestRated(cuisine);
*/
代码二#
(大神代码)[https://leetcode.cn/circle/discuss/sWfXxC/]
class FoodRatings {
public:
typedef pair<int,string> pis;
unordered_map<string ,pis> fc;
unordered_map<string ,set<pis>> cs;
int n;
FoodRatings(vector<string>& foods, vector<string>& cuisines, vector<int>& ratings) {
n =foods.size();
for(int i=0;i<n;i++){
fc[foods[i]]={ratings[i],cuisines[i]};
cs[cuisines[i]].insert(pis(-ratings[i],foods[i]));
}
}
void changeRating(string food, int newRating) {
pis& t=fc[food];
cs[t.second].erase({-t.first,food});
t.first=newRating;
cs[t.second].insert({-newRating,food});
}
string highestRated(string cuisine) {
return cs[cuisine].begin()->second;
}
};
/**
* Your FoodRatings object will be instantiated and called as such:
* FoodRatings* obj = new FoodRatings(foods, cuisines, ratings);
* obj->changeRating(food,newRating);
* string param_2 = obj->highestRated(cuisine);
*/
```
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)