981. Time Based Key-Value Store
https://leetcode.com/problems/time-based-key-value-store/
ask timestamp is ordered, increasing?
for the question, so we want the value ( timestamp <= query input's timestamp, closest one)
so can leverage treemap's floorKey() (treeMap<timestmap, value> or
2. use BS to find the closest value (timestamp <= query input's timestamp)
HashMap + list , Binary search
from constraint:
All the timestamps
timestampofsetare strictly increasing.
so in actually, we can use bs in List
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 "";
}T: set: O(1), get: O(1) + O(nlogn), n is list len
S: O(m*n), m - hashmap size, n - each list size
HashMap + TreeMap
T: set: O(1), get: O(1) + O(nlogn), n is treemap size
S: O(m*n), m - hashmap size, n - each treemap size
Last updated
Was this helpful?