LeetCode题解(1797):设计一个验证系统(Python)
原创
©著作权归作者所有:来自51CTO博客作者Changxing长行的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目:原题链接(中等)
标签:设计、哈希表、堆
解法
| 时间复杂度
| 空间复杂度
| 执行用时
|
Ans 1 (Python)
|
|
| 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)