|
| 1 | +class TimeMap { |
| 2 | + |
| 3 | + /** Initialize your data structure here. */ |
| 4 | + Map<String, List<Entry>> map; |
| 5 | + public TimeMap() { |
| 6 | + map = new HashMap<>(); |
| 7 | + } |
| 8 | + |
| 9 | + public void set(String key, String value, int timestamp) { |
| 10 | + map.computeIfAbsent(key, k -> new ArrayList<>()).add(new Entry(value, timestamp)); |
| 11 | + } |
| 12 | + |
| 13 | + public String get(String key, int timestamp) { |
| 14 | + if (!map.containsKey(key)) { |
| 15 | + return ""; |
| 16 | + } |
| 17 | + |
| 18 | + return binarySearch(map.get(key), 0, map.get(key).size() - 1, timestamp); |
| 19 | + } |
| 20 | + |
| 21 | + private String binarySearch(List<Entry> entries, int left, int right, int timestamp) { |
| 22 | + int idx = Integer.MIN_VALUE; |
| 23 | + while (left <= right) { |
| 24 | + int mid = (left + right) / 2; |
| 25 | + if (entries.get(mid).timestamp == timestamp) { |
| 26 | + return entries.get(mid).value; |
| 27 | + } |
| 28 | + else if (entries.get(mid).timestamp > timestamp) { |
| 29 | + right = mid - 1; |
| 30 | + } |
| 31 | + else { |
| 32 | + idx = Math.max(idx, mid); |
| 33 | + left = mid + 1; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + return idx == Integer.MIN_VALUE ? "" : entries.get(idx).value; |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +class Entry { |
| 42 | + String value; |
| 43 | + int timestamp; |
| 44 | + |
| 45 | + public Entry(String value, int timestamp) { |
| 46 | + this.value = value; |
| 47 | + this.timestamp = timestamp; |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * Your TimeMap object will be instantiated and called as such: |
| 53 | + * TimeMap obj = new TimeMap(); |
| 54 | + * obj.set(key,value,timestamp); |
| 55 | + * String param_2 = obj.get(key,timestamp); |
| 56 | + */ |
0 commit comments