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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。