第 303 场力扣周赛(TreeSet)

第一次参加力扣周赛,我真的是菜到GUCCI
https://leetcode.cn/circle/discuss/sWfXxC/

  1. 第一个出现两次的字母 6124. 第一个出现两次的字母
  2. 相等行列对 6125. 相等行列对
  3. 设计食物评分系统 6126
//TreeSet
class Solution {
  class FoodRatings {

    class FoodWithRate {
      String food;
      int rate;
      String cuisine;//保存烹饪方式的映射

      public FoodWithRate(String f, String cuisine, int rate) {
        food = f;
        this.cuisine = cuisine;
        this.rate = rate;
      }
    }

    HashMap<String, TreeSet<FoodWithRate>> map = new HashMap<>();//保存各个烹饪方式中所有food的排序结果
    HashMap<String, FoodWithRate> foodIndexMap = new HashMap<>();//对象索引

    public FoodRatings(String[] foods, String[] cuisines, int[] ratings) {
      int n = foods.length;
      for (int i = 0; i < n; i++) {
        String f = foods[i], c = cuisines[i];
        int rate = ratings[i];
        TreeSet<FoodWithRate> set = map.getOrDefault(c, new TreeSet<>((o1, o2) -> o1.rate != o2.rate ? o2.rate - o1.rate : o1.food.compareTo(o2.food)));
        FoodWithRate foodWithRate = new FoodWithRate(f, c, rate);
        foodIndexMap.put(f, foodWithRate);//保存对象索引
        set.add(foodWithRate);//加入新food对象, 由TreeSet比较器来排序
        map.put(c, set);
      }
    }

    public void changeRating(String food, int newRating) {
      FoodWithRate legacyFood = foodIndexMap.get(food);
      TreeSet<FoodWithRate> foodWithRates = map.get(legacyFood.cuisine);//找烹饪方式
      foodWithRates.remove(legacyFood);//根据索引删除老节点
      FoodWithRate foodWithRate = new FoodWithRate(food, legacyFood.cuisine, newRating);
      foodIndexMap.put(food, foodWithRate);
      foodWithRates.add(foodWithRate);//加入新节点,由TreeSet比较器来排序
    }

    public String highestRated(String c) {
      TreeSet<FoodWithRate> foodWithRates = map.get(c);
      return foodWithRates.first().food;//找到最大值
    }
  }
}

作者:hu-li-hu-wai
链接:https://leetcode.cn/problems/design-a-food-rating-system/solution/by-hu-li-hu-wai-h8xy/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值