-
Notifications
You must be signed in to change notification settings - Fork 0
/
TimeMap.java
64 lines (49 loc) · 1.51 KB
/
TimeMap.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.pallamsetty.binarysearch;
/*
* Leetcode 981
* */
import com.pallamsetty.binarysearch.helpers.TimeValueMap;
import java.util.HashMap;
public class TimeMap {
HashMap<String, TimeValueMap> map;
public TimeMap() {
map = new HashMap<>();
}
public void set(String key, String value, int timestamp) {
TimeValueMap tvMap;
if(!map.containsKey(key)) {
map.put(key, new TimeValueMap());
}
tvMap = map.get(key);
tvMap.add(value, timestamp);
map.put(key, tvMap);
}
public String get(String key, int timestamp) {
TimeValueMap tvMap = map.get(key);
if(tvMap == null
|| tvMap.getSize() == 0
|| timestamp < tvMap.timestamps.get(0)) {
return "";
}
if(timestamp >= tvMap.timestamps.get(tvMap.getSize() - 1)) {
return tvMap.values.get(tvMap.getSize() - 1);
}
int left = 0;
int right = tvMap.getSize() - 1;
while(left < right) {
int mid = left + (right - left) / 2;
if(tvMap.timestamps.get(mid) == timestamp) {
return tvMap.values.get(mid);
}
if(tvMap.timestamps.get(mid) > timestamp) {
right = mid - 1;
} else {
left = mid + 1;
}
}
if(tvMap.timestamps.get(left) == timestamp) {
return tvMap.values.get(left);
}
return tvMap.values.get(Math.max(left - 1, 0));
}
}