mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2025-12-06 08:54:07 +00:00
day 42: 981-time-based-key-value-store
This commit is contained in:
parent
832df6f66e
commit
a148ec2b74
13
981-time-based-key-value-store/driver.cpp
Normal file
13
981-time-based-key-value-store/driver.cpp
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
#include "soln.cpp"
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
TimeMap timeMap;
|
||||||
|
timeMap.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1.
|
||||||
|
cout << timeMap.get("foo", 1) << endl; // return "bar"
|
||||||
|
cout << timeMap.get("foo", 3) << endl; // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar".
|
||||||
|
timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4.
|
||||||
|
cout << timeMap.get("foo", 4) << endl; // return "bar2"
|
||||||
|
cout << timeMap.get("foo", 5) << endl; // return "bar2"
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
51
981-time-based-key-value-store/soln.cpp
Normal file
51
981-time-based-key-value-store/soln.cpp
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
#include <bits/stdc++.h>
|
||||||
|
using namespace std;
|
||||||
|
class TimeMap
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
unordered_map<string, vector<pair<int, string>>> timemap;
|
||||||
|
TimeMap()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
void set(string key, string value, int timestamp)
|
||||||
|
{
|
||||||
|
timemap[key].push_back({timestamp, value});
|
||||||
|
}
|
||||||
|
|
||||||
|
string get(string key, int timestamp)
|
||||||
|
{
|
||||||
|
if (timemap.find(key) == timemap.end())
|
||||||
|
{
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
else if (timemap[key].size() == 1)
|
||||||
|
{
|
||||||
|
return timemap[key][0].first <= timestamp ? timemap[key][0].second : "";
|
||||||
|
}
|
||||||
|
// binary search
|
||||||
|
int low = 0, high = timemap[key].size(), mid;
|
||||||
|
while (low < high)
|
||||||
|
{
|
||||||
|
mid = low + (high - low) / 2;
|
||||||
|
if (timemap[key][mid].first <= timestamp)
|
||||||
|
{
|
||||||
|
low = mid + 1;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
high = mid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Now, low points to the element that succeeds the given timestamp
|
||||||
|
// so we want the one before it
|
||||||
|
return low > 0 && low <= timemap[key].size() ? timemap[key][low - 1].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);
|
||||||
|
*/
|
||||||
Loading…
x
Reference in New Issue
Block a user