981. 基於時間的鍵值儲存

WrRan發表於2024-09-10
題目連結 981. 基於時間的鍵值儲存
思路 雜湊+二分
題解連結 雜湊表+二分
關鍵點 理解題意
時間複雜度 \(O(\log n)\)
空間複雜度 \(O(n)\)

程式碼實現:

class TimeMap:

    def __init__(self):
        self.dct = defaultdict(list)

    def set(self, key: str, value: str, timestamp: int) -> None:
        self.dct[key].append((timestamp, value))

    def get(self, key: str, timestamp: int) -> str:
        lst = self.dct[key]
        left, right = -1, len(lst)
        while left + 1 < right:
            mid = (left + right) // 2
            if lst[mid][0] > timestamp:
                right = mid
            else:
                left = mid
        if right == 0:
            return ""
        else:
            return self.dct[key][right - 1][1]
Python-標準庫
class TimeMap:

    def __init__(self):
        self.dct = defaultdict(list)

    def set(self, key: str, value: str, timestamp: int) -> None:
        self.dct[key].append((timestamp, value))

    def get(self, key: str, timestamp: int) -> str:
        upper_bound = bisect_right(self.dct[key], timestamp, key=lambda _: _[0])
        if upper_bound == 0:
            return ""
        else:
            return self.dct[key][upper_bound-1][1]

相關文章