981. Time Based Key-Value Store
HashMap + list , Binary search (append to list set() is better! O(1))
protected String binarySearch(List<Data> list, int time) {
int low = 0, high = list.size() - 1;
while (low +1 < high) {
int mid = (low + high) >> 1;
if (list.get(mid).time <= time) {
low = mid;
} else {
high = mid;
}
}
// we want closest time, so compare end first
if (list.get(high).time <= time) {
return list.get(high).val;
}
if (list.get(low).time <= time) {
return list.get(low).val;
}
return "";
}HashMap + TreeMap
Last updated