150强访谈简单

基于时间的键值存储

“基于时间的键值存储”问题的详细指南和 Python 实现。

问题陈述

简单

设计一个基于时间的键值数据结构,可以存储同一键在不同时间戳的多个值,并在某个时间戳检索该键的值。

实现 TimeMap 类:

- TimeMap() 初始化对象。

- set(key: str, value: str, timestamp: int) 在给定时间 timestamp 存储键 key 和值 value

- get(key: str, timestamp: int) -> str 返回一个值,使得 set 之前使用 timestamp_prev <= timestamp 被调用。如果有多个这样的值,则返回与最大的 timestamp_prev 关联的值。如果没有值,则返回 ""

约束条件
  • 1 <= key.length, value.length <= 100
  • key and value consist of lowercase English letters and digits
  • 1 <= timestamp <= 10^7
  • All timestamps of set are strictly increasing for each key
  • At most 2 * 10^5 calls will be made to set and get

示例

Example 1
Input
["TimeMap", "set", "get", "get", "set", "get", "get"]
[[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]
Output
[None, None, "bar", "bar", None, "bar2", "bar2"]
Explanation

set("foo", "bar", 1): stores bar at time 1. get("foo", 1): returns "bar". get("foo", 3): returns "bar" (latest value at or before time 3). set("foo", "bar2", 4): stores bar2 at time 4. get("foo", 4): returns "bar2". get("foo", 5): returns "bar2".

Need a Hint?
考虑使用二分搜索特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。