-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathSolution.java
72 lines (56 loc) · 1.85 KB
/
Solution.java
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
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* @author Oleg Cherednik
* @since 11.02.2019
*/
public class Solution {
public static void main(String... args) {
TimeMap<Integer, Integer> d = new TimeMap<>();
d.set(1, 1, 0);
d.set(1, 2, 2);
System.out.println(d.get(1, 1)); // 1
System.out.println(d.get(1, 3)); // 2
d.set(1, 1, 5);
System.out.println(d.get(1, 0)); // 1
System.out.println(d.get(1, 10)); // 1
d.set(1, 1, 0);
d.set(1, 2, 0);
System.out.println(d.get(1, 0)); // 1
}
public static final class TimeMap<K, V> {
private final Map<K, Set<TimeEntry<V>>> map = new HashMap<>();
public void set(K key, V value, int time) {
if (!map.containsKey(key))
map.put(key, new TreeSet<>());
map.get(key).add(new TimeEntry<>(time, value));
}
public V get(K key, int time) {
Set<TimeEntry<V>> entries = map.getOrDefault(key, Collections.emptySet());
if (entries.isEmpty())
return null;
V value = null;
for (TimeEntry<V> entry : entries) {
if (entry.time > time)
break;
value = entry.value;
}
return value;
}
private static final class TimeEntry<V> implements Comparable<TimeEntry<V>> {
private final int time;
private final V value;
public TimeEntry(int time, V value) {
this.time = time;
this.value = value;
}
@Override
public int compareTo(TimeEntry<V> entry) {
return Integer.compare(time, entry.time);
}
}
}
}