|
1 | 1 | class TimeMap { |
2 | | - private Map<String, List<Node>> hm; |
| 2 | + Map<String, TreeMap<Integer, String>> m; |
3 | 3 |
|
4 | 4 | public TimeMap() { |
5 | | - hm = new HashMap<>(); |
| 5 | + m = new HashMap<>(); |
6 | 6 | } |
7 | 7 |
|
8 | 8 | public void set(String key, String value, int timestamp) { |
9 | | - hm.putIfAbsent(key, new ArrayList<>()); |
10 | | - hm.get(key).add(new Node(timestamp, value)); |
| 9 | + m.putIfAbsent(key, new TreeMap<>()); |
| 10 | + m.get(key).put(timestamp, value); |
11 | 11 | } |
12 | 12 |
|
13 | 13 | public String get(String key, int timestamp) { |
14 | | - if (!hm.containsKey(key)) { |
| 14 | + if (!m.containsKey(key)) { |
15 | 15 | return ""; |
16 | 16 | } |
17 | 17 |
|
18 | | - List<Node> nodes = hm.get(key); |
19 | | - int low = 0, high = nodes.size() - 1; |
| 18 | + Integer result = m.get(key).floorKey(timestamp); |
20 | 19 |
|
21 | | - while (low < high) { |
22 | | - int mid = low + (high - low) / 2; |
23 | | - |
24 | | - if (nodes.get(mid).timestamp == timestamp) { |
25 | | - return nodes.get(mid).value; |
26 | | - } |
27 | | - |
28 | | - if (nodes.get(mid).timestamp < timestamp) { |
29 | | - if (nodes.get(mid + 1).timestamp > timestamp) { |
30 | | - return nodes.get(mid).value; |
31 | | - } |
32 | | - |
33 | | - low = mid + 1; |
34 | | - } else { |
35 | | - high = mid - 1; |
36 | | - } |
37 | | - } |
38 | | - |
39 | | - return nodes.get(low).timestamp <= timestamp ? nodes.get(low).value : ""; |
40 | | - } |
41 | | - |
42 | | - private class Node { |
43 | | - private int timestamp; |
44 | | - private String value; |
45 | | - |
46 | | - public Node(int t, String v) { |
47 | | - timestamp = t; |
48 | | - value = v; |
| 20 | + if (result == null) { |
| 21 | + return ""; |
49 | 22 | } |
| 23 | + return m.get(key).get(result); |
50 | 24 | } |
51 | 25 | } |
0 commit comments