题目描述 (周赛185 # 2)
一堆订单数据,把它们整理为统计表格
算法
class Solution {
public:
vector<vector<string>> displayTable(vector<vector<string>>& orders) {
/*①统计不同 fooditem。并排序,造一个有序集合
②遍历orders ---> 构建res表格
③ 根据Table 编号排序构造 res
④输出: res数组加上标题 并压入ans,把它输出出来即可。
*/
set<string> foods;
for (const auto &v : orders)
foods.insert(v[2]);
int cnt = 1;
unordered_map<string, int> fp;
for (const auto &s : foods) fp[s] = cnt ++;
vector<vector<int>> res;
cnt = 0;
unordered_map<string, int> tp;
for (const auto &v : orders){
if (tp.find(v[1]) == tp.end()) {
tp[v[1]] = cnt;
res.push_back(vector<int>(foods.size() + 1)); //构造res
res[cnt][0] = stoi(v[1]);
cnt ++;
}
res[tp[v[1]]][fp[v[2]]] ++;
}
sort(res.begin(), res.end()); //有序集合
vector<vector<string>> ans;
ans.push_back(vector<string>(1));
ans[0][0] = "Table"; //开始写(表格)第一行第一列(即第一个)标题
for (const auto &v : foods) ans[0].push_back(v); //剩下的标题
for (int i = 0; i < res.size(); i++){
ans.push_back(vector<string>(foods.size() + 1));
for (int j = 0; j <= foods.size(); j++)
ans[i + 1][j] = to_string(res[i][j]); //把res压入ans答案表格中
}
return ans;
}
};