Skip to content

Commit c3c43be

Browse files
authored
Update 981-time-based-key-value-store.js
1 parent 6643f09 commit c3c43be

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

981-time-based-key-value-store.js

+50
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,56 @@ TimeMap.prototype.set = function(key, value, timestamp) {
1616
this.hash[key].push([value, timestamp])
1717
};
1818

19+
/**
20+
* @param {string} key
21+
* @param {number} timestamp
22+
* @return {string}
23+
*/
24+
TimeMap.prototype.get = function(key, timestamp) {
25+
if(this.hash[key] == null) return ''
26+
const arr = this.hash[key]
27+
28+
let l = 0, r = arr.length - 1;
29+
while(l <= r) {
30+
const pick = Math.floor((l + r) / 2);
31+
if (arr[pick][1] < timestamp) {
32+
l = pick + 1;
33+
} else if (arr[pick][1] > timestamp) {
34+
r = pick - 1
35+
} else {
36+
return arr[pick][0];
37+
}
38+
}
39+
return arr[r]?.[0] || ''
40+
};
41+
42+
/**
43+
* Your TimeMap object will be instantiated and called as such:
44+
* var obj = new TimeMap()
45+
* obj.set(key,value,timestamp)
46+
* var param_2 = obj.get(key,timestamp)
47+
*/
48+
49+
// another
50+
51+
/**
52+
* Initialize your data structure here.
53+
*/
54+
const TimeMap = function() {
55+
this.hash = {}
56+
};
57+
58+
/**
59+
* @param {string} key
60+
* @param {string} value
61+
* @param {number} timestamp
62+
* @return {void}
63+
*/
64+
TimeMap.prototype.set = function(key, value, timestamp) {
65+
if(this.hash[key] == null) this.hash[key] = []
66+
this.hash[key].push([value, timestamp])
67+
};
68+
1969
/**
2070
* @param {string} key
2171
* @param {number} timestamp

0 commit comments

Comments
 (0)