题目链接:
1418. 点菜展示表
解题思路[哈希表 模拟]:
- 按照题目要求, 需要先统计一共有多少种食物;
- 遍历原集合, 按照桌次进行分组, 并对桌号进行排序;
- 遍历每个桌号分组后的集合, 匹配食物种类统计每一桌, 每一种食物的数量, 并组装返回值
解题代码:
class Solution {
public List<List<String>> displayTable(List<List<String>> orders) {
List<List<String>> result = new ArrayList<>();
//1. 统计共有多少种食物
List<String> tableSerise = new ArrayList<>();
for(List<String> list : orders){
if(!tableSerise.contains(list.get(2))){
tableSerise.add(list.get(2));
}
}
tableSerise.sort(String::compareTo); //组装表头
tableSerise.add(0,"Table");
result.add(tableSerise);
//2. 按桌统计, 统计各自具有的食物在已有的所有食物的数量
Map<String, List<List<String>>> group = orders.stream().collect(Collectors.groupingBy(l-> l.get(1)));
//3. 组装返回结果
group.entrySet().stream().sorted((e1, e2)->Integer.parseInt(e1.getKey())- Integer.parseInt(e2.getKey())).forEach(m-> {
List<List<String>> foodList = m.getValue();
List<String> table = new ArrayList<>();
table.add(m.getKey());
for (int i = 1; i < tableSerise.size(); i++) {
String foodName = tableSerise.get(i);
int count = 0;
for(int j = 0; j< foodList.size(); j++){
if(foodList.get(j).get(2).equals(foodName)){
count++;
}
}
table.add(String.valueOf(count));
}
result.add(table);
});
return result;
}
}
提交记录[20210706]:
执行用时:103 ms, 在所有 Java 提交中击败了9.64%的用户
内存消耗:62.8 MB, 在所有 Java 提交中击败了67.47%的用户