日志速率限制器

Submission

运行时间: 75 ms

内存: 23.1 MB

class Logger:

    def __init__(self):
        self.dct = {}

    def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
        if message not in self.dct:
            self.dct[message] = [timestamp]
            return True
        else:
            if timestamp - self.dct[message][-1] >= 10:
                self.dct[message].append(timestamp)
                return True
            else:
                return False



# Your Logger object will be instantiated and called as such:
# obj = Logger()
# param_1 = obj.shouldPrintMessage(timestamp,message)

Explain

该题解使用了一个字典 dct 来记录每个消息上一次打印的时间戳。当收到一个新的消息打印请求时,先检查字典中是否已有该消息的记录:如果没有记录,则将当前时间戳记录到字典中,并返回 True 表示可以打印;如果有记录,则比较当前时间戳与字典中记录的上一次打印时间戳之差是否大于等于 10,如果是则更新字典中的时间戳并返回 True,否则返回 False 表示不应打印。

时间复杂度: O(1)

空间复杂度: O(M),其中 M 是不同消息的数量

class Logger:

    def __init__(self):
        self.dct = {}  # 用于存储消息和对应的时间戳列表

    def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
        if message not in self.dct:  # 如果是新消息
            self.dct[message] = [timestamp]  # 记录当前时间戳
            return True
        else:
            if timestamp - self.dct[message][-1] >= 10:  # 如果与上一次打印的时间戳之差大于等于 10
                self.dct[message].append(timestamp)  # 更新时间戳列表
                return True
            else:
                return False  # 不应打印,直接返回 False