2353. Design a Food Rating System

T: FoodRatings() : O(nlogn), changeRating(): O(logn), highestRated: O(1)

S: O(n)

```java
class FoodRatings {
    class Cuisine {
        String cuisine;
        int rating;
        Cuisine(String cuisine, int rating) {
            this.cuisine = cuisine;
            this.rating = rating;
        }
    }
    class Food {
        String food;
        int rating;
        Food(int rating, String food) {
            this.food = food;
            this.rating = rating;
        }
    }

    private Map<String, Cuisine> foodMap;
    private Map<String, TreeSet<Food>> sortedMap;
    public FoodRatings(String[] foods, String[] cuisines, int[] ratings) {
        foodMap = new HashMap<>();
        sortedMap = new HashMap<>();
        for (int i = 0; i < foods.length; i++) {
            foodMap.put(foods[i], new Cuisine(cuisines[i], ratings[i]));
            sortedMap.putIfAbsent(cuisines[i], new TreeSet<>((a, b) -> {
                int compareRating = b.rating - a.rating; // 由大到小
                if (compareRating == 0) { // same key
                    return a.food.compareTo(b.food);
                }
                return compareRating; // return large one
            }));
            sortedMap.get(cuisines[i]).add(new Food(ratings[i], foods[i]));
        }
    }
    
    public void changeRating(String food, int newRating) {
        Cuisine cuisine = foodMap.get(food);
        int oldRating = cuisine.rating;
        foodMap.get(food).rating = newRating;
        sortedMap.get(cuisine.cuisine).remove(new Food(oldRating, food));
        sortedMap.get(cuisine.cuisine).add(new Food(newRating, food));
    }
    
    public String highestRated(String cuisine) {
        Food first = sortedMap.get(cuisine).first(); // 由大到小, so 取 first
        if (first != null) {
            return first.food;
        }
        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);

sortedMap:
 cuisine -> rating, food

 food, (cuisine,rating) 
 */
```

Last updated