题目:​​原题链接​​(中等)

标签:设计、哈希表、堆

解法

时间复杂度

空间复杂度

执行用时

Ans 1 (Python)

LeetCode题解(1797):设计一个验证系统(Python)_leetcode

LeetCode题解(1797):设计一个验证系统(Python)_leetcode_02

112ms (97.87%)

Ans 2 (Python)

Ans 3 (Python)

解法一:

class AuthenticationManager:

def __init__(self, timeToLive: int):
self.ttl = timeToLive
self.timeline = []
self.tokens = {}

def generate(self, token: str, current: int) -> None:
self._remove(current)
if token not in self.tokens: # 题目保证独一无二
self.tokens[token] = current + self.ttl
heapq.heappush(self.timeline, (current + self.ttl, token))

def renew(self, token: str, current: int) -> None:
self._remove(current)
if token in self.tokens:
self.tokens[token] = current + self.ttl
heapq.heappush(self.timeline, (current + self.ttl, token))

def countUnexpiredTokens(self, current: int) -> int:
self._remove(current)
return len(self.tokens)

def _remove(self, current):
"""移除过期验证码"""
while self.timeline and self.timeline[0][0] <= current:
time, token = heapq.heappop(self.timeline)
if token in self.tokens and self.tokens[token] == time:
self.tokens.pop(token)