基于时间的键值存储
题目描述:
创建一个基于时间的键值存储类 TimeMap,它支持下面两个操作:
- set(string key, string value, int timestamp)
存储键 key、值 value,以及给定的时间戳 timestamp。- get(string key, int timestamp)
返回先前调用 set(key, value, timestamp_prev) 所存储的值,其中 timestamp_prev <= timestamp。
如果有多个这样的值,则返回对应最大的 timestamp_prev 的那个值。
如果没有值,则返回空字符串("")。示例:
输入:inputs = [“TimeMap”,“set”,“get”,“get”,“set”,“get”,“get”], inputs = [[],[“foo”,“bar”,1],[“foo”,1],[“foo”,3],[“foo”,“bar2”,4],[“foo”,4],[“foo”,5]]
输出:[null,null,“bar”,“bar”,null,“bar2”,“bar2”]
解释:
TimeMap kv;
kv.set(“foo”, “bar”, 1); // 存储键 “foo” 和值 “bar” 以及时间戳 timestamp = 1
kv.get(“foo”, 1); // 输出 “bar”
kv.get(“foo”, 3); // 输出 “bar” 因为在时间戳 3 和时间戳 2 处没有对应 “foo” 的值,所以唯一的值位于时间戳 1 处(即 “bar”)
kv.set(“foo”, “bar2”, 4);
kv.get(“foo”, 4); // 输出 “bar2”
kv.get(“foo”, 5); // 输出 “bar2”
提示:
- 所有的键/值字符串都是小写的。
- 所有的键/值字符串长度都在 [1, 100] 范围内。
- 所有 TimeMap.set 操作中的时间戳 timestamps 都是严格递增的。
- 1 <= timestamp <= 107
- TimeMap.set 和 TimeMap.get 函数在每个测试用例中将(组合)调用总计 120000 次。
解法
- 首先比较直观的思路是建立 key-value&time 的字典,用于得到不同的 key 对应的一些信息;
- 因为 set 的时间戳是严格递增的,所以简单使用一个列表来存储时间戳即可;对应地,使用一个列表存储该时间戳的 value。在寻找的时候,因为严格递增,所以可以使用二分法来降低复杂度。
代码
class TimeMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.key2list = {}
def set(self, key: str, value: str, timestamp: int) -> None:
if key not in self.key2list:
self.key2list[key] = [[], []]
self.key2list[key][0].append(timestamp)
self.key2list[key][1].append(value)
def get(self, key: str, timestamp: int) -> str:
if key not in self.key2list or timestamp < self.key2list[key][0][0]:
return ""
time_list = self.key2list[key][0]
left, right = 0, len(time_list) - 1
while left < right:
mid = left + (right - left + 1) // 2
if time_list[mid] < timestamp:
left = mid
elif time_list[mid] > timestamp:
right = mid - 1
else:
return self.key2list[key][1][mid]
return self.key2list[key][1][left]
# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)
测试结果
执行用时:476 ms, 在所有 Python3 提交中击败了 97.96% 的用户
内存消耗:67.3 MB, 在所有 Python3 提交中击败了 88.78% 的用户
说明
算法题来源:力扣(LeetCode)