-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2353_Design_a_Food_Rating_System.java
62 lines (54 loc) · 1.8 KB
/
2353_Design_a_Food_Rating_System.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* 2353. Design a Food Rating System
* Problem Link: https://leetcode.com/problems/design-a-food-rating-system/
* Difficulty: Medium
*
* Solution Created by: Muhammad Khuzaima Umair
* LeetCode : https://leetcode.com/mkhuzaima/
* Github : https://github.com/mkhuzaima
* LinkedIn : https://www.linkedin.com/in/mkhuzaima/
*/
class FoodRatings {
class FoodItem implements Comparable<FoodItem> {
String food, cuisine;
int rating;
public FoodItem(String food, String cuisine, int rating) {
this.food = food;
this.cuisine = cuisine;
this.rating = rating;
}
public int compareTo(FoodItem other) {
if (other.rating != this.rating) {
return other.rating - this.rating; // reversed
}
return this.food.compareTo(other.food);
}
}
Map<String, FoodItem> map; // food name to item
Set<FoodItem> set; // sorted set
public FoodRatings(String[] foods, String[] cuisines, int[] ratings) {
map = new HashMap<>();
set = new TreeSet<>();
for (int i = 0; i < foods.length; i++) {
FoodItem fi = new FoodItem(foods[i], cuisines[i], ratings[i]);
map.put(foods[i], fi);
set.add(fi);
}
}
public void changeRating(String food, int newRating) {
FoodItem fi = map.get(food);
set.remove(fi); // reinsert in set to keep sorted
fi.rating = newRating;
set.add(fi);
}
public String highestRated(String cuisine) {
Iterator<FoodItem> it = set.iterator();
while (it.hasNext()) {
FoodItem fi = it.next();
if (fi.cuisine.equals(cuisine)) {
return fi.food;
}
}
return null;
}
}