LeetCode6126:Set自定义排序规则方法

题目#

6126. 设计食物评分系统

算法思路#

  • 利用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);
 */
```
posted @   lxp_blog  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示
主题色彩