Skip to content

Commit 6643f09

Browse files
authoredApr 3, 2021
Create 981-time-based-key-value-store.js
1 parent db6de7a commit 6643f09

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
 

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

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Initialize your data structure here.
3+
*/
4+
const TimeMap = function() {
5+
this.hash = {}
6+
};
7+
8+
/**
9+
* @param {string} key
10+
* @param {string} value
11+
* @param {number} timestamp
12+
* @return {void}
13+
*/
14+
TimeMap.prototype.set = function(key, value, timestamp) {
15+
if(this.hash[key] == null) this.hash[key] = []
16+
this.hash[key].push([value, timestamp])
17+
};
18+
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
29+
while(l < r) {
30+
const mid = l + ((r - l) >> 1)
31+
if(arr[mid][1] <= timestamp) {
32+
l = mid + 1
33+
} else {
34+
r = mid
35+
}
36+
}
37+
38+
if(r === 0) return ''
39+
return arr[r - 1][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+
*/

0 commit comments

Comments
 (0)