【每日一题Day113】LC1797设计一个验证系统 | 哈希表
创始人
2024-05-24 07:53:54
0

设计一个验证系统【LC1797】

你需要设计一个包含验证码的验证系统。每一次验证中,用户会收到一个新的验证码,这个验证码在 currentTime 时刻之后 timeToLive 秒过期。如果验证码被更新了,那么它会在 currentTime (可能与之前的 currentTime 不同)时刻延长 timeToLive 秒。

请你实现 AuthenticationManager 类:

  • AuthenticationManager(int timeToLive) 构造 AuthenticationManager 并设置 timeToLive 参数。
  • generate(string tokenId, int currentTime) 给定 tokenId ,在当前时间 currentTime 生成一个新的验证码。
  • renew(string tokenId, int currentTime) 将给定 tokenId未过期 的验证码在 currentTime 时刻更新。如果给定 tokenId 对应的验证码不存在或已过期,请你忽略该操作,不会有任何更新操作发生。
  • countUnexpiredTokens(int currentTime) 请返回在给定 currentTime 时刻,未过期 的验证码数目。

如果一个验证码在时刻 t 过期,且另一个操作恰好在时刻 t 发生(renew 或者 countUnexpiredTokens 操作),过期事件 优先于 其他操作。

  • 思路:

    使用哈希表存储每个验证码的过期时间,哈希表的key为本次请求的tokenId,value为该验证码的过期时间,为请求的currentTime+timeToLive

    • generate(string tokenId, int currentTime):在哈希表中添加新的验证码及其过期时间
    • renew(string tokenId, int currentTime) :如果该tokenId不存在或者存在并且未过期时,更新过期时间
    • countUnexpiredTokens(int currentTime) :遍历哈希表,统计过期时间大于 currentTime 的验证码数目
  • 实现

    class AuthenticationManager {Map idToEnd;int timeToLive;public AuthenticationManager(int timeToLive) {this.timeToLive = timeToLive;idToEnd = new HashMap<>();}public void generate(String tokenId, int currentTime) {idToEnd.put(tokenId, currentTime + timeToLive);}public void renew(String tokenId, int currentTime) {if (idToEnd.containsKey(tokenId) && idToEnd.get(tokenId) > currentTime){idToEnd.put(tokenId, currentTime + timeToLive); }}public int countUnexpiredTokens(int currentTime) {int size = 0;for (var node : idToEnd.entrySet()){if (node.getValue() > currentTime){size++;}}return size;}
    }/*** Your AuthenticationManager object will be instantiated and called as such:* AuthenticationManager obj = new AuthenticationManager(timeToLive);* obj.generate(tokenId,currentTime);* obj.renew(tokenId,currentTime);* int param_3 = obj.countUnexpiredTokens(currentTime);*/
    
    • 复杂度
      • 时间复杂度:generate、renew的时间复杂度为O(1)O(1)O(1),countUnexpiredTokens的时间复杂度为O(n)O(n)O(n)
      • 空间复杂度:O(n)O(n)O(n)

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...