2026/06/14

[LeetCode] 981 Time Based Key-Value Store

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class TimeMap {
public:
  using TimeMapEntry = pair<int, string>;
  unordered_map<string, vector<TimeMapEntry>> timeMap;
  TimeMap() {}

  void set(string key, string value, int timestamp) {
    timeMap[key].push_back(make_pair(timestamp, value));
  }

  string get(string key, int timestamp) {
    if (timeMap.find(key) == timeMap.end())
      return "";

    auto &v = timeMap[key];
    auto it = upper_bound(
        v.begin(), v.end(), timestamp,
        [](int t, const TimeMapEntry &entry) { return t < entry.first; });
    if (it == v.begin())
      return "";
    return prev(it)->second;
  }
};

/**
 * Your TimeMap object will be instantiated and called as such:
 * TimeMap* obj = new TimeMap();
 * obj->set(key,value,timestamp);
 * string param_2 = obj->get(key,timestamp);
 */