| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Original file line number | Diff line number | Diff 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 | + } | ||
| Back | FazBrowse Home | New Git URL |
0 commit comments