题解 | #设计有setAll功能的哈希表#

设计有setAll功能的哈希表

https://www.nowcoder.com/practice/7c4559f138e74ceb9ba57d76fd169967

#include <iostream>
#include <unordered_map>
#include <utility>
using namespace std;

class MyMap 
{
    // pair <value, cnt> // 加时间戳技术
    std::unordered_map<int, std::pair<int, int>> umap;
    int setAllValue;
    int setAllTime{0};
    int cnt{1};
public:
    void put(int key, int value) 
    {
        umap[key] = {value, cnt++}; 
    }

    int get(int key) 
    {
        if (!containsKey(key)) {
            return -1;
        }

        if (umap[key].second < setAllTime) {
            return setAllValue;
        }
        return umap[key].first;
    }

    bool containsKey(int key)
    {
        if (umap.find(key) == umap.end()) {
            return false;
        }
        return true;
    }

    void setAll(int value)
    {
        setAllValue = value;
        setAllTime = cnt++;
    }

};

int main() {
    MyMap mymap;
    int n;
    std::cin >> n;
    int op;
    int key;
    int value;
    for (int i = 0; i < n; i++) {
        std::cin >> op;
        switch (op) {
            case 1:
                std::cin >> key >> value;
                mymap.put(key, value);
                break;
            case 2:
                std::cin >> key;
                std::cout << mymap.get(key) << std::endl;
                break;
            case 3:
                std::cin >> value;
                mymap.setAll(value);
                break;
        }

    }
}
// 64 位输出请用 printf("%lld")

按照左神的讲的加时间戳解决

https://www.bilibili.com/video/BV1nF411y7rD/?spm_id_from=333.999.0.0&vd_source=8ea6dc6c02215b66383cf6ab9791e3b4

全部评论

相关推荐

在笔试的大西瓜很矫健:校招数分不用想了,这经历和学历都不够用,大厂更别想,初筛都过不了,说点不好听的小厂数分都进不去(小厂也是假数分),要两个对口实习+3个项目(或者3+2),而且要有含金量才能补一点你的学历劣势。 建议刷实习,社招找数分,校招看运气,能入行业就行,可以运营转数分
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务