-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path981-time-based-key-value-store.ts
More file actions
51 lines (43 loc) · 1.26 KB
/
Copy path981-time-based-key-value-store.ts
File metadata and controls
51 lines (43 loc) · 1.26 KB
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
/**
* Solution explanation:
* Map of key, to [timestamp, value]
* get does binary search for timestamp, and return the corresponding value
*/
class TimeMap {
private values: Map<string, [number, string][]>
constructor() {
this.values = new Map<string, [number, string][]>();
}
set(key: string, value: string, timestamp: number): void {
const list = this.values.get(key);
if (list) {
list.push([timestamp, value]);
} else {
this.values.set(key, [[timestamp, value]])
}
}
get(key: string, timestamp: number): string {
const list = this.values.get(key);
if (!list) return "";
let left = 0;
let right = list.length - 1;
let result = "";
while (left <= right) {
const mid = Math.floor((left + right) / 2);
const [time, value] = list[mid];
if (time <= timestamp) {
result = value;
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
}
/**
* 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)
*/