class TimeMap {
Map<String, List<String>> keyVal;
Map<String, List<Integer>> timeSeriesMap;
public TimeMap() {
keyVal = new HashMap<>();
timeSeriesMap = new HashMap<>();
}
public void set(String key, String value, int timestamp) {
List<String> lsVal;
List<Integer> lsTime;
if(timeSeriesMap.containsKey(key)){
lsTime = timeSeriesMap.get(key);
lsTime.add(timestamp);
lsVal = keyVal.get(key);
lsVal.add(value);
} else {
lsTime = new ArrayList<>();
lsTime.add(timestamp);
lsVal = new ArrayList<>();
lsVal.add(value);
}
keyVal.put(key, lsVal);
timeSeriesMap.put(key, lsTime);
}
public String get(String key, int timestamp) {
if(timeSeriesMap.containsKey(key)){
int index = getIndexForTimeStamp(timeSeriesMap.get(key), timestamp);
if( index == -1) return "";
return keyVal.get(key).get(index);
} else {
return "";
}
}
private int getIndexForTimeStamp(List<Integer> lsTime, int timestamp) {
int s = 0 , e = lsTime.size() - 1;
if ( timestamp < lsTime.get(0) ) return -1;
if ( timestamp >= lsTime.get(e) ) return e;
while ( s < e-1 ) {
int mid = s + (e - s) / 2 ;
if (lsTime.get(mid) == timestamp) return mid;
if (lsTime.get(mid) > timestamp) e = mid - 1;
if (lsTime.get(mid) < timestamp) s = mid;
}
return s;
}
}
/**
* Your TimeMap object will be instantiated and called as such:
* TimeMap obj = new TimeMap();
* obj.set(key,value,timestamp);
* String param_2 = obj.get(key,timestamp);
*/