File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments