forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0981-time-based-key-value-store.js
52 lines (44 loc) · 1.25 KB
/
0981-time-based-key-value-store.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* Your TimeMap object will be instantiated and called as such:
* var obj = new TimeMap()
* obj.set(key,value,timestamp)
* var param_2 = obj.get(key,timestamp)
*/
class TimeMap {
constructor() {
this.map = {};
}
/**
* @param {string} key
* @param {string} value
* @param {number} timestamp
* Time O(1) | Space O(1)
* @return {void}
*/
set(key, value, timestamp) {
const bucket = this.map[key] || [];
this.map[key] = bucket;
bucket.push([value, timestamp]);
}
/**
* @param {string} key
* @param {number} timestamp
* Time O(log(N)) | Space O(1)
* @return {string}
*/
get(key, timestamp, value = '', bucket = this.map[key] || []) {
let [left, right] = [0, bucket.length - 1];
while (left <= right) {
const mid = (left + right) >> 1;
const [guessValue, guessTimestamp] = bucket[mid];
const isTargetGreater = guessTimestamp <= timestamp;
if (isTargetGreater) {
value = guessValue;
left = mid + 1;
}
const isTargetLess = timestamp < guessTimestamp;
if (isTargetLess) right = mid - 1;
}
return value;
}
}