leetCode JS/TS专属题 2622. 有时间限制的缓存

思路: 

       使用Map + 定时器来解决,我们可以创建一个Map,在set()方法中先判断Map中是否有还未过期的键值对,如果存在,先清掉之前设置的定时器,防止之前的定时器将当前设置的键值对删掉,然后再设置新的定时器,定时器的作用就是经过duration毫秒后,删掉当前键值对,就代表它过期了。

TypeScript代码:

class TimeLimitedCache {
    private timeMap: Map<number, {
        val: number,
        timer: ReturnType<typeof setTimeout>
    }>;
    
    constructor() {
      this.timeMap = new Map();
    }

    set(key: number, value: number, duration: number): boolean {
      const flag: boolean = this.timeMap.has(key);
      if(flag) {
         clearTimeout(this.timeMap.get(key).timer);
      }
      this.timeMap.set(key, {
          val: value,
          timer: setTimeout(() => {
              this.timeMap.delete(key);
          }, duration)
      });

      return flag;
    }

    get(key: number): number {
      return this.timeMap.has(key) ? this.timeMap.get(key).val : -1;
    }

	  count(): number {
      return this.timeMap.size;
    }
}

/**
 * Your TimeLimitedCache object will be instantiated and called as such:
 * var obj = new TimeLimitedCache()
 * obj.set(1, 42, 1000); // false
 * obj.get(1) // 42
 * obj.count() // 1
 */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值