码迷,mamicode.com
首页 > 其他好文 > 详细

LC 981. Time Based Key-Value Store

时间:2019-02-04 16:47:53      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:oid   previous   create   call   cal   mes   public   support   mission   

Create a timebased key-value store class TimeMap, that supports two operations.

1. set(string key, string value, int timestamp)

  • Stores the key and value, along with the given timestamp.

2. get(string key, int timestamp)

  • Returns a value such that set(key, value, timestamp_prev) was called previously, with timestamp_prev <= timestamp.
  • If there are multiple such values, it returns the one with the largest timestamp_prev.
  • If there are no values, it returns the empty string ("").
Runtime: 212 ms, faster than 55.01% of C++ online submissions for Time Based Key-Value Store.
Memory Usage: 57 MB, less than 100.00% of C++ online submissions for Time Based Key-Value Store.

 

class TimeMap {
private:
  unordered_map<string, map<int, string>> mp;
  vector<int> tvec;
public:
  /** Initialize your data structure here. */
  TimeMap() {}

  void set(string key, string value, int timestamp) {
    mp[key][timestamp] = value;
  }

  string get(string key, int timestamp) {
    if(!mp.count(key)) return "";
    if(mp[key].count(timestamp)) return mp[key][timestamp];
    for(auto it = mp[key].rbegin(); it != mp[key].rend(); it++) {
      if(it->first > timestamp) continue;
      else {
        return it->second;
      }
    }
    return "";
  }
};

 

LC 981. Time Based Key-Value Store

标签:oid   previous   create   call   cal   mes   public   support   mission   

原文地址:https://www.cnblogs.com/ethanhong/p/10351773.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!