Sunday, August 4, 2019

Leetcode 981: Time Based Key-Value Store

https://leetcode.com/problems/time-based-key-value-store/description/



Notes:

This question is pretty straightforward, and it is essentially a question of data structure + binary search. See the code below,
  1. class TimeMap {
  2. public:
  3.     /** Initialize your data structure here. */
  4.     TimeMap() {
  5.     }
  6.     void set(string key, string value, int timestamp) {
  7.         if(ump.count(key) == 0) ump[key].push_back({timestamp, value});
  8.         auto it = upper_bound(ump[key].begin(), ump[key].end(), pair<int, string>(timestamp, ""));
  9.         ump[key].insert(it, {timestamp, value});
  10.     }
  11.     string get(string key, int timestamp) {
  12.         if(ump.count(key) == 0) return "";
  13.         auto it = upper_bound(ump[key].begin(), ump[key].end(), pair<int, string>(timestamp, ""));
  14.         if(it != ump[key].end() && it->first == timestamp) return it->second;
  15.         if(it == ump[key].begin()) return "";
  16.         return (it-1)->second;
  17.     }
  18. private:
  19.     unordered_map<string, vector<pair<int, string>>> ump;
  20. };
  21. /**
  22.  * Your TimeMap object will be instantiated and called as such:
  23.  * TimeMap* obj = new TimeMap();
  24.  * obj->set(key,value,timestamp);
  25.  * string param_2 = obj->get(key,timestamp);
  26.  */

It should be noticed that inside the upper_bound(), the type of pair has to be written explicitly as pair<int, string>, otherwise compiler error will occur.

Another way using a different structure. Pay attention to the property of map.upper_bound().

  1. int _=[](){//increase run spead
  2. ios::sync_with_stdio(false);
  3. cin.tie(nullptr);
  4. return 0;
  5. }();
  6. class TimeMap {
  7. public:
  8.     /** Initialize your data structure here. */
  9.     TimeMap() {
  10.        
  11.     }
  12.    
  13.     void set(string key, string value, int timestamp) {
  14.         ump[key][timestamp] = value;
  15.     }
  16.     string get(string key, int timestamp) {
  17.         if(ump.count(key) == 0) return "";
  18.         auto it = ump[key].upper_bound(timestamp); //find the upper bound of the key of the map...
  19.         if(it == ump[key].begin()) return "";
  20.         return (--it)->second;
  21.     }
  22. private:
  23.     unordered_map<string, map<int, string>> ump;
  24. };
  25. /**
  26.  * Your TimeMap object will be instantiated and called as such:
  27.  * TimeMap* obj = new TimeMap();
  28.  * obj->set(key,value,timestamp);
  29.  * string param_2 = obj->get(key,timestamp);
  30.  */

No comments:

Post a Comment