|
| 1 | +package leetcode.medium; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.Map; |
| 6 | +import java.util.Optional; |
| 7 | + |
| 8 | +class TimeStampedValue { |
| 9 | + public int timestamp; |
| 10 | + public String value; |
| 11 | + |
| 12 | + public TimeStampedValue(int timestamp, String value) { |
| 13 | + this.timestamp = timestamp; |
| 14 | + this.value = value; |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +public class TimeMap { |
| 19 | + Map<String, ArrayList<TimeStampedValue>> entriesByKey; |
| 20 | + |
| 21 | + public TimeMap() { |
| 22 | + // Constructor to initialize the TimeMap object |
| 23 | + entriesByKey = new HashMap<>(); |
| 24 | + } |
| 25 | + |
| 26 | + public void set(String key, String value, int timestamp) { |
| 27 | + // Implementation for setting the value at a specific timestamp |
| 28 | + if(!entriesByKey.containsKey(key)) { |
| 29 | + entriesByKey.put(key, new ArrayList<>()); |
| 30 | + } |
| 31 | + ArrayList<TimeStampedValue> timeStampedValues = entriesByKey.get(key); |
| 32 | + timeStampedValues.add(new TimeStampedValue(timestamp, value)); |
| 33 | + } |
| 34 | + |
| 35 | + public String get(String key, int timestamp) { |
| 36 | + if(!entriesByKey.containsKey(key)) return ""; |
| 37 | + |
| 38 | + ArrayList<TimeStampedValue> timeStampedValues = entriesByKey.get(key); |
| 39 | + Optional<TimeStampedValue> timeStamp = |
| 40 | + binarySearchTimestamp(timeStampedValues, timestamp); |
| 41 | + if(timeStamp.isEmpty()) { |
| 42 | + return ""; |
| 43 | + } |
| 44 | + |
| 45 | + return timeStamp.get().value; |
| 46 | + } |
| 47 | + |
| 48 | + private Optional<TimeStampedValue> binarySearchTimestamp( |
| 49 | + ArrayList<TimeStampedValue> arr, int target) { |
| 50 | + int left = 0, right = arr.size() - 1; |
| 51 | + int matchIndex = -1; |
| 52 | + |
| 53 | + while (left <= right) { |
| 54 | + int mid = left + (right - left) / 2; |
| 55 | + TimeStampedValue cur = arr.get(mid); |
| 56 | + if(cur.timestamp <= target) { |
| 57 | + matchIndex = mid; |
| 58 | + left = mid + 1; |
| 59 | + } |
| 60 | + else { |
| 61 | + right = mid - 1; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + if(matchIndex == -1) { |
| 66 | + return Optional.empty(); |
| 67 | + } |
| 68 | + return Optional.of(arr.get(matchIndex)); |
| 69 | + } |
| 70 | +} |
0 commit comments