FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Add: TimeMap · OmarShawky1/Problem-Solving-Map@3e9cf98 · GitHub

Commit 3e9cf98

Browse files
committed
Add: TimeMap
1 parent 3be7169 commit 3e9cf98

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package arrays.sortingAndSearching.binarySearch;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
import java.util.TreeMap;
6+
7+
// Most Maintainable Code. For fastest code, just implement your own RB-Tree.
8+
public class TimeMap {
9+
10+
private final Map<String, TreeMap<Integer, String>> data;
11+
12+
public TimeMap() {
13+
// Initialize a hashmap to store key-value pairs.
14+
data = new HashMap<>();
15+
}
16+
17+
public void set(String key, String value, int timestamp) {
18+
// If the key is not already in the hashmap, create a new TreeMap.
19+
data.putIfAbsent(key, new TreeMap<>());
20+
21+
// Add the timestamp and value to the TreeMap associated with the key.
22+
data.get(key).put(timestamp, value);
23+
}
24+
25+
public String get(String key, int timestamp) {
26+
// If the key is not in the hashmap, return an empty string.
27+
if (!data.containsKey(key)) return "";
28+
29+
// Get the TreeMap associated with the key.
30+
TreeMap<Integer, String> timestamps = data.get(key);
31+
32+
// Use TreeMap's floorKey method to find the largest timestamp less than or equal to the given timestamp.
33+
Integer floorKey = timestamps.floorKey(timestamp);
34+
35+
// If floorKey is null, no such timestamp exists, return an empty string.
36+
if (floorKey == null) return "";
37+
38+
// Return the value associated with the found timestamp.
39+
return timestamps.get(floorKey);
40+
}
41+
42+
public static void test() {
43+
// Example usage:
44+
TimeMap timeMap = new TimeMap();
45+
timeMap.set("foo", "bar", 1);
46+
System.out.println(timeMap.get("foo", 1)); // Output: "bar"
47+
System.out.println(timeMap.get("foo", 3)); // Output: "bar"
48+
System.out.println(timeMap.get("foo", 5)); // Output: "bar"
49+
}
50+
}

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL