-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproblem_097.js
74 lines (62 loc) Β· 1.59 KB
/
problem_097.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class TimeMap {
constructor() {
this.map = new Map();
}
/**
* Set the key to value for t = time
* @param {any} key
* @param {any} value
* @param {number} time
*/
set(key, value, time) {
if (!this.map.has(key)) {
const arr = [{ value, time }];
this.map.set(key, arr);
} else {
const arr = this.map.get(key);
// check all elements in arr.
// If one contains the same value. Rewrite the time
// else push new element of value, time
let found = false;
const updatedArr = arr.map(element => {
const { value: eValue } = element;
if (eValue !== value) return element;
found = true;
return {
value,
time
};
});
if (!found) {
updatedArr.push({ value, time });
}
this.map.set(key, updatedArr);
}
}
/**
* Gets the key at time t
* @param {any} key
* @param {number} time
* @return {any}
*/
get(key, time) {
// get biggest time smaller or equal to time
if (!this.map.has(key)) return null;
const arr = this.map.get(key);
let value = null;
let biggestTimeSmallerThanTime = null;
for (let i = 0; i < arr.length; i++) {
const { value: eValue, time: eTime } = arr[i];
if (eTime > time) continue;
if (value === null && biggestTimeSmallerThanTime === null) {
value = eValue;
biggestTimeSmallerThanTime = eTime;
}
if (eTime >= biggestTimeSmallerThanTime) {
value = eValue;
biggestTimeSmallerThanTime = eTime;
}
}
return value;
}
}