1. 题目来源
链接:1418. 点菜展示表
2. 题目解析
某次周赛的第二题,印象深刻。
本题最难的是要抽象如何将数据进行存储,由于需要使用字典序进行输出,那么就用了 map<> 省去了排序这个步骤。
具体思路看代码即可,现在做本题感觉轻松好多啊hh
时间复杂度:
O
(
n
l
o
g
n
)
O(nlogn)
O(nlogn)
空间复杂度:
O
(
n
)
O(n)
O(n)
哈希表+模拟+STL
class Solution {
public:
vector<vector<string>> displayTable(vector<vector<string>>& orders) {
vector<vector<string>> res;
map<int, map<string, int>> mmp; // [餐桌, [菜, 菜的数量]]
map<string, int> m; // [菜, 菜的数量]
// 初始化 map,构建餐桌与菜的关系
for (auto &e : orders) {
string name = e[0];
int table = stoi(e[1]);
string food = e[2];
m[food] ++ ;
mmp[table][food] ++ ;
}
// 构建第一行
vector<string> p;
p.push_back("Table");
for (auto &[k, v] : m) p.push_back(k);
res.push_back(p);
// 遍历每个餐桌,每个菜品,对应菜品数量
for (auto &[table, mp] : mmp) {
vector<string> t;
t.push_back(to_string(table));
for (auto &[food, cnt] : m)
t.push_back(to_string(mp[food]));
res.push_back(t);
}
return res;
}
};
优化点菜展示:哈希表与字典序算法应用
本文讲述了作者在一次周赛中解决菜品展示问题的思路,利用哈希表和STL模拟,实现了按字典序输出菜品和数量,展示了高效的O(nlogn)时间复杂度和O(n)空间复杂度解决方案。

被折叠的 条评论
为什么被折叠?



