由于C++的时间戳最多精确到毫秒,程序运行时间不足1毫秒,所以使用自定义的int计数。
#include <iostream> #include <unordered_map> #include <time.h> using namespace std; class MyMap { private: unordered_map<int, int> map; unordered_map<int, int> map_time; int setAllTime = 0; int allVal; int time = 0; public: void put(int key, int val) { map[key] = val; map_time[key] = time++; } int get(int key) { if (!containsKey(key)) return -1; return map_time[key] < setAllTime ? allVal : map[key]; } bool containsKey(int key) { return map.find(key) != map.end() ? true : false; } void setAll(int val) { setAllTime = time++; allVal = val; } }; int main() { int num; cin >> num; MyMap map; for(int i = 0; i < num; i++) { int cmd; cin >> cmd; if (cmd == 1) // put { int key, val; cin >> key >> val; map.put(key, val); }else if (cmd == 2) // get { int key; cin >> key; cout << map.get(key) << endl; }else if (cmd == 3) // setAll { int val; cin >> val; map.setAll(val); } } return 0; }