LeetCode 题解工作台

设计食物评分系统

设计一个支持下述操作的食物评分系统: 修改 系统中列出的某种食物的评分。 返回系统中某一类烹饪方式下评分最高的食物。 实现 FoodRatings 类: FoodRatings(String[] foods, String[] cuisines, int[] ratings) 初始化系统。食物由 f…

category

6

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

我们可以使用哈希表 来存储每种烹饪方式下的食物,其中键是烹饪方式,值是一个有序集合,有序集合的每个元素是一个二元组 $(\textit{rating}, \textit{food})$,按照评分从高到低排序,如果评分相同,则按照食物名字的字典序从小到大排序。 我们还可以使用哈希表 来存储每种食物的评分和烹饪方式。即 $\textit{g}[\textit{food}] = (\textit{r…

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

设计一个支持下述操作的食物评分系统:

  • 修改 系统中列出的某种食物的评分。
  • 返回系统中某一类烹饪方式下评分最高的食物。

实现 FoodRatings 类:

  • FoodRatings(String[] foods, String[] cuisines, int[] ratings) 初始化系统。食物由 foodscuisinesratings 描述,长度均为 n
    • foods[i] 是第 i 种食物的名字。
    • cuisines[i] 是第 i 种食物的烹饪方式。
    • ratings[i] 是第 i 种食物的最初评分。
  • void changeRating(String food, int newRating) 修改名字为 food 的食物的评分。
  • String highestRated(String cuisine) 返回指定烹饪方式 cuisine 下评分最高的食物的名字。如果存在并列,返回 字典序较小 的名字。

注意,字符串 x 的字典序比字符串 y 更小的前提是:x 在字典中出现的位置在 y 之前,也就是说,要么 xy 的前缀,或者在满足 x[i] != y[i] 的第一个位置 i 处,x[i] 在字母表中出现的位置在 y[i] 之前。

 

示例:

输入
["FoodRatings", "highestRated", "highestRated", "changeRating", "highestRated", "changeRating", "highestRated"]
[[["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]], ["korean"], ["japanese"], ["sushi", 16], ["japanese"], ["ramen", 16], ["japanese"]]
输出
[null, "kimchi", "ramen", null, "sushi", null, "ramen"]

解释
FoodRatings foodRatings = new FoodRatings(["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]);
foodRatings.highestRated("korean"); // 返回 "kimchi"
                                    // "kimchi" 是分数最高的韩式料理,评分为 9 。
foodRatings.highestRated("japanese"); // 返回 "ramen"
                                      // "ramen" 是分数最高的日式料理,评分为 14 。
foodRatings.changeRating("sushi", 16); // "sushi" 现在评分变更为 16 。
foodRatings.highestRated("japanese"); // 返回 "sushi"
                                      // "sushi" 是分数最高的日式料理,评分为 16 。
foodRatings.changeRating("ramen", 16); // "ramen" 现在评分变更为 16 。
foodRatings.highestRated("japanese"); // 返回 "ramen"
                                      // "sushi" 和 "ramen" 的评分都是 16 。
                                      // 但是,"ramen" 的字典序比 "sushi" 更小。

 

提示:

  • 1 <= n <= 2 * 104
  • n == foods.length == cuisines.length == ratings.length
  • 1 <= foods[i].length, cuisines[i].length <= 10
  • foods[i]cuisines[i] 由小写英文字母组成
  • 1 <= ratings[i] <= 108
  • foods 中的所有字符串 互不相同
  • 在对 changeRating 的所有调用中,food 是系统中食物的名字。
  • 在对 highestRated 的所有调用中,cuisine 是系统中 至少一种 食物的烹饪方式。
  • 最多调用 changeRatinghighestRated 总计 2 * 104
lightbulb

解题思路

方法一:哈希表 + 有序集合

我们可以使用哈希表 d\textit{d} 来存储每种烹饪方式下的食物,其中键是烹饪方式,值是一个有序集合,有序集合的每个元素是一个二元组 (rating,food)(\textit{rating}, \textit{food}),按照评分从高到低排序,如果评分相同,则按照食物名字的字典序从小到大排序。

我们还可以使用哈希表 g\textit{g} 来存储每种食物的评分和烹饪方式。即 g[food]=(rating,cuisine)\textit{g}[\textit{food}] = (\textit{rating}, \textit{cuisine})

在构造函数中,我们遍历 foods\textit{foods}cuisines\textit{cuisines}ratings\textit{ratings},将每种食物的评分和烹饪方式存储到 d\textit{d}g\textit{g} 中。

changeRating\textit{changeRating} 函数中,我们首先获取食物 food\textit{food} 的原评分 oldRating\textit{oldRating} 和烹饪方式 cuisine\textit{cuisine},然后更新 g[food]\textit{g}[\textit{food}] 的评分为 newRating\textit{newRating},并从 d[cuisine]\textit{d}[\textit{cuisine}] 中删除 (oldRating,food)(\textit{oldRating}, \textit{food}),并将 (newRating,food)(\textit{newRating}, \textit{food}) 添加到 d[cuisine]\textit{d}[\textit{cuisine}] 中。

highestRated\textit{highestRated} 函数中,我们直接返回 d[cuisine]\textit{d}[\textit{cuisine}] 的第一个元素的食物名字即可。

时间复杂度方面,构造函数的时间复杂度为 O(nlogn)O(n \log n),其中 nn 是食物的数量。其余操作的时间复杂度为 O(logn)O(\log n)。空间复杂度为 O(n)O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class FoodRatings:

    def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
        self.d = defaultdict(SortedList)
        self.g = {}
        for food, cuisine, rating in zip(foods, cuisines, ratings):
            self.d[cuisine].add((-rating, food))
            self.g[food] = (rating, cuisine)

    def changeRating(self, food: str, newRating: int) -> None:
        oldRating, cuisine = self.g[food]
        self.g[food] = (newRating, cuisine)
        self.d[cuisine].remove((-oldRating, food))
        self.d[cuisine].add((-newRating, food))

    def highestRated(self, cuisine: str) -> str:
        return self.d[cuisine][0][1]


# Your FoodRatings object will be instantiated and called as such:
# obj = FoodRatings(foods, cuisines, ratings)
# obj.changeRating(food,newRating)
# param_2 = obj.highestRated(cuisine)
speed

复杂度分析

指标
时间O((n + m) \log n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for efficient management of both hash maps and priority queues.

  • question_mark

    The ability to handle tie cases by lexicographical order is a key part of this solution.

  • question_mark

    The candidate should optimize updates to the rating system to ensure the solution can handle large inputs.

warning

常见陷阱

外企场景
  • error

    Failing to update the heap correctly after changing a food's rating.

  • error

    Not handling lexicographical order correctly in case of ties when querying the highest rated food.

  • error

    Using inefficient data structures that result in poor performance when handling large inputs.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Extending the system to support multiple cuisines and more complex rating updates.

  • arrow_right_alt

    Adding additional features such as filtering by food category or cuisine.

  • arrow_right_alt

    Handling edge cases such as empty inputs or invalid cuisine names.

help

常见问题

外企场景

设计食物评分系统题解:数组·哈希·扫描 | LeetCode #2353 中等