这是我参与新手入门的第1篇文章
一、题目描述:
给你一个数组 orders,表示客户在餐厅中完成的订单,确切地说, orders[i]=[customerNamei,tableNumberi,foodItemi] ,其中 customerNamei 是客户的姓名,tableNumberi 是客户所在餐桌的桌号,而 foodItemi 是客户点的餐品名称。
请你返回该餐厅的 点菜展示表 。在这张表中,表中第一行为标题,其第一列为餐桌桌号 “Table” ,后面每一列都是按字母顺序排列的餐品名称。接下来每一行中的项则表示每张餐桌订购的相应餐品数量,第一列应当填对应的桌号,后面依次填写下单的餐品数量。
注意:客户姓名不是点菜展示表的一部分。此外,表中的数据行应该按餐桌桌号升序排列。
示例 :
输入:orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]] 输出:[["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]]
二、思路分析:
实现思路
分析题目,需要对订单信息进行统计
- 客户的姓名是无用数据,忽略
- 按照 table 对数据分组, 使用 HashMap, table作为 key, 食物的名称和数量作为 value
- 返回结果 第一行,需要对 食物按字典序排序 ,使用 HashSet 记录食物的种类
- 表中的数据行应该按餐桌桌号升序排列
遇到的问题
不是一次 AC 的, 最初是使用 String 集合 存储的 table 数据, 在使用 Collections.sort 对 table 进行排序时是按照字典序排的,不符合题目的要求(按餐桌桌号升序排列),因此 改用 Integer 集合存储 table
三、AC 代码
public List<List<String>> displayTable(List<List<String>> orders) {
if (orders == null || orders.size() == 0) {
return new ArrayList<>();
}
// <table : <food : count>>
Map<Integer, Map<String, Integer>> map = new HashMap<>();
Set<String> foodSet = new HashSet<>();
List<List<String>> res = new ArrayList<>();
for (List<String> list : orders) {
int table = Integer.parseInt(list.get(1));
String food = list.get(2);
foodSet.add(food);
Map<String, Integer> foodMap = map.getOrDefault(table, new HashMap<>());
int count = foodMap.getOrDefault(food, 0);
foodMap.put(food, ++count);
map.put(table, foodMap);
}
// 排序
List<Integer> tables = new ArrayList<>(map.keySet());
Collections.sort(tables);
List<String> foodList = new ArrayList<>(foodSet);
Collections.sort(foodList);
// 第一行的数据
List<String> temp = new ArrayList<>();
temp.add("Table");
temp.addAll(foodList);
res.add(new ArrayList<>(temp));
// 每个 table 对应的 食物 数量
for (Integer table : tables) {
temp.clear();
temp.add(String.valueOf(table));
Map<String, Integer> foodMap = map.getOrDefault(table, new HashMap<>());
for (String food : foodList) {
int count = foodMap.getOrDefault(food, 0);
temp.add(String.valueOf(count));
}
res.add(new ArrayList<>(temp));
}
return res;
}