[Medium] LeetCode JS 30 - 2622. Cache with Time Limit

2024年3月6日

💎 加入 E+ 成長計畫 與超過 300+ 位軟體工程師一同在社群中成長,並且獲得更多的軟體工程學習資源

LeetCode 30 Days of JavaScript

本題來自 LeetCode 的 30 天 JacaScript 挑戰

2622. Cache with Time Limit

題目描述

建立一個 TimeLimitedCache 類別,這個類別能讓你取得與設定鍵值對 (key-value pair),同時能為每個鍵值對設定一個「過期時間」。

具體要實作三個方法:

  • set(key, value, duration): 接受一個整數的鍵 key、一個整數值 value,以及一個毫秒為單位的時間 duration。當持續時間結束後,這個鍵值對將不能被存取。如果相同且未過期的鍵存在,則回傳 true,若不存在則回傳 false。如果這個鍵已經存在,其值與持續時間都應該被新傳入的 valueduration 覆寫。
  • get(key):如果存在未過期的鍵,回傳其對應的值。若沒有相對應的鍵,則回傳 1
  • count():回傳現存未過期的鍵的總數量。
// 範例
輸入:
actions = ["TimeLimitedCache", "set", "get", "count", "get"]
values = [[], [1, 42, 100], [1], [], [1]]
timeDelays = [0, 0, 50, 50, 150]

輸出: [null, false, 42, 1, -1]

解釋:
At t=0, 建立 TimeLimitedCache
At t=0,  (1: 42) 加入,該鍵值對會持續 100毫秒。因為原本還沒有 1 這個鍵,所以回傳 false
At t=50, 查看 key=1,因為還沒到 100 毫秒,還沒過期,所以回傳 42
At t=50, 呼叫 count() 目前有一個鍵 (key=1),所以回傳 1
At t=100, key=1 過期
At t=150, 這時呼叫 get(1),因為沒有任何鍵,所以回傳 -1

本題解答

以下是本題的解答,詳細解題思路可以在 E+ 成長計畫看到

解法

解法一

var TimeLimitedCache = function () {
  this.cache = new Map();
};

TimeLimitedCache.prototype.set = function (key, value, duration) {
  const found = this.cache.has(key);
  if (found) {
    clearTimeout(this.cache.get(key).timerId);
  }
  this.cache.set(key, {
    value,
    timerId: setTimeout(() => this.cache.delete(key), duration),
  });
  return found;
};

TimeLimitedCache.prototype.get = function (key) {
  if (this.cache.has(key)) {
    return this.cache.get(key).value;
  } else {
    return -1;
  }
};

TimeLimitedCache.prototype.count = function () {
  return this.cache.size;
};

解法二

class TimeLimitedCache {
  constructor() {
    this.cache = new Map();
  }

  set(key, value, duration) {
    const found = this.cache.has(key);

    if (found) {
      clearTimeout(this.cache.get(key).timerId);
    }

    this.cache.set(key, {
      value,
      value,
      timerId: setTimeout(() => {
        this.cache.delete(key);
      }, duration),
    });

    return found;
  }

  get(key) {
    return this.cache.has(key) ? this.cache.get(key).value : -1;
  }

  count() {
    return this.cache.size;
  }
}
🧵 如果你想收到最即時的內容更新,可以在 FacebookInstagram 上追蹤我們