Skip to content

Commit fcce68a

Browse files
authored
Create 2353_Design_a_Food_Rating_System.java
1 parent 516c44a commit fcce68a

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// id: 2353
2+
// Name: Design a Food Rating System
3+
// link: https://leetcode.com/problems/design-a-food-rating-system/
4+
// Difficulty: Medium
5+
6+
class FoodRatings {
7+
8+
class FoodItem implements Comparable<FoodItem> {
9+
String food, cuisine;
10+
int rating;
11+
public FoodItem(String food, String cuisine, int rating) {
12+
this.food = food;
13+
this.cuisine = cuisine;
14+
this.rating = rating;
15+
}
16+
public int compareTo(FoodItem other) {
17+
if (other.rating != this.rating) {
18+
return other.rating - this.rating; // reversed
19+
}
20+
return this.food.compareTo(other.food);
21+
}
22+
}
23+
24+
Map<String, FoodItem> map; // food name to item
25+
Set<FoodItem> set; // sorted set
26+
27+
public FoodRatings(String[] foods, String[] cuisines, int[] ratings) {
28+
map = new HashMap<>();
29+
set = new TreeSet<>();
30+
for (int i = 0; i < foods.length; i++) {
31+
FoodItem fi = new FoodItem(foods[i], cuisines[i], ratings[i]);
32+
map.put(foods[i], fi);
33+
set.add(fi);
34+
}
35+
}
36+
37+
public void changeRating(String food, int newRating) {
38+
FoodItem fi = map.get(food);
39+
set.remove(fi); // reinsert in set to keep sorted
40+
fi.rating = newRating;
41+
set.add(fi);
42+
}
43+
44+
public String highestRated(String cuisine) {
45+
Iterator<FoodItem> it = set.iterator();
46+
47+
while (it.hasNext()) {
48+
FoodItem fi = it.next();
49+
if (fi.cuisine.equals(cuisine)) {
50+
return fi.food;
51+
}
52+
}
53+
return null;
54+
}
55+
}
56+

0 commit comments

Comments
 (0)