[MSTL] lc1418. 点菜展示表(模拟+哈希表)

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ypuyu

如果帮助到你,可以请作者喝水~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值