题解 | #设计有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")
按照左神的讲的加时间戳解决