当前位置:网站首页>2022.07.24(LC_6126_设计食物评分系统)
2022.07.24(LC_6126_设计食物评分系统)
2022-07-25 11:45:00 【Leeli9316】

方法:Map+TreeSet
class FoodRatings {
//用一个食物信息类表示食物的食物名、烹饪方式、评分
class FoodInfo {
String food;
String cuisine;
int rating;
FoodInfo(String food, String cuisine, int rating) {
this.food = food;
this.cuisine = cuisine;
this.rating = rating;
}
}
//食物名对应一个食物信息类
Map<String, FoodInfo> foodInfoMap = new HashMap<>();
//烹饪方式对应一个TreeSet,TreeSet存放所有这种烹饪方式的食物,并按题意自定义排序
Map<String, TreeSet<FoodInfo>> cuisineMap = new HashMap<>();
public FoodRatings(String[] foods, String[] cuisines, int[] ratings) {
for (int i = 0; i < foods.length; i++) {
FoodInfo foodInfo = new FoodInfo(foods[i], cuisines[i], ratings[i]);
foodInfoMap.put(foods[i], foodInfo);
if (!cuisineMap.containsKey(cuisines[i])) {
cuisineMap.put(cuisines[i], new TreeSet<>(((o1, o2) -> {
//对烹饪方式相同食物的排序规则:首先按评分降序排列,
//如果评分相同,则按字典序对食物名字升序排列。
if (o1.rating != o2.rating) return o2.rating - o1.rating;
return o1.food.compareTo(o2.food);
})));
}
//在烹饪方式对应的TreeSet中添加食物信息
cuisineMap.get(cuisines[i]).add(foodInfo);
}
}
public void changeRating(String food, int newRating) {
FoodInfo foodInfo = foodInfoMap.get(food);
//改变评分时需要把TreeSet中的评分信息删掉,不然更改评分后的位置是错的
//即先删除,然后改评分,最后加入TreeSet找到正确位置
cuisineMap.get(foodInfo.cuisine).remove(foodInfo);
foodInfo.rating = newRating;
cuisineMap.get(foodInfo.cuisine).add(foodInfo);
}
public String highestRated(String cuisine) {
//直接返回烹饪方式对应的TreeSet的第一个食物名字
return cuisineMap.get(cuisine).first().food;
}
}注意:
- 更新评分时先删除再重新插入, 触发红黑树中节点的旋转。
边栏推荐
猜你喜欢

Unexpected rollback exception analysis and transaction propagation strategy for nested transactions

Communication bus protocol I: UART

919. Complete binary tree inserter: simple BFS application problem

NLP的基本概念1

web编程(二)CGI相关

Atomic 原子类

Atomic atomic class

RestTemplate与Ribbon简单使用

Crawler crawls dynamic website

第一个scrapy爬虫
随机推荐
Script set random user_ agent
aaaaaaaaaaA heH heH nuN
Pytorch project practice - fashionmnist fashion classification
【2】 Grid data display stretch ribbon (take DEM data as an example)
通过Referer请求头实现防盗链
Client open download, welcome to try
Ansible
【11】 Production and adjustment of vector and grid data Legends
monit安装和使用
R language ggplot2 visualization: visualize the scatter diagram, add text labels to some data points in the scatter diagram, and use geom of ggrep package_ text_ The repl function avoids overlapping l
Fault tolerant mechanism record
通信总线协议一 :UART
马斯克的“灵魂永生”:一半炒作,一半忽悠
【AI4Code】《CodeBERT: A Pre-Trained Model for Programming and Natural Languages》 EMNLP 2020
NLP知识----pytorch,反向传播,预测型任务的一些小碎块笔记
R语言使用lm函数构建多元回归模型(Multiple Linear Regression)、使用step函数构建前向逐步回归模型筛选预测变量的最佳子集、scope参数指定候选预测变量
【三】DEM山体阴影效果
Atomic 原子类
selenium使用———xpath和模拟输入和模拟点击协作
【ROS进阶篇】第九讲 URDF的编程优化Xacro使用