From fe7f413ec9e6859ee993b03a12669697706aa643 Mon Sep 17 00:00:00 2001 From: shintaroyoshida20 Date: Thu, 22 May 2025 07:02:15 +0900 Subject: [PATCH 1/2] feat : #26 add the empty markdown for creating a PR --- others/linked-list/lru-cache/answer.md | 39 ++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 others/linked-list/lru-cache/answer.md diff --git a/others/linked-list/lru-cache/answer.md b/others/linked-list/lru-cache/answer.md new file mode 100644 index 0000000..e11d06e --- /dev/null +++ b/others/linked-list/lru-cache/answer.md @@ -0,0 +1,39 @@ +# 146. LRU Cache + +## STEP1 + +### 発想 + +### 想定されるユースケース + +### 何が分からなかったか? + +```javascript +``` + +## STEP2 + +```javascript +``` + +## STEP3 + +```javascript +``` + +## 感想 + +### コメント集を読んで + +## 他の人のPRを読んで + +## その他の方法 + +### コードの良し悪し + +* `*0` + +* `*1` + +## 調べたこと + From 1debd1e399ea4ac05e49036df7d606775df1fa50 Mon Sep 17 00:00:00 2001 From: shintaroyoshida20 Date: Sun, 6 Jul 2025 11:38:39 +0900 Subject: [PATCH 2/2] feat : #26 add the STEP1 --- others/linked-list/lru-cache/answer.md | 48 ++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/others/linked-list/lru-cache/answer.md b/others/linked-list/lru-cache/answer.md index e11d06e..4e241a8 100644 --- a/others/linked-list/lru-cache/answer.md +++ b/others/linked-list/lru-cache/answer.md @@ -4,11 +4,59 @@ ### 発想 +- 優先度つきキューで、キャッシュを保存する。 +getを行う際には、一度popし、その後にpushする。 +putを行う際には、 + キーが存在しない場合には最も古いキャッシュをpopし、キャッシュをpushする。 + キーが存在する場合には一度キャッシュをpopし、新しい時刻でpushしなおす。 + ### 想定されるユースケース ### 何が分からなかったか? +- 以下のコードはTimeout Limit Exceededが発生。 + ```javascript +const LRUCache = function(capacity) { + this.caches = new PriorityQueue((a, b) => a.clock - b.clock) + this.capacity = capacity + this.clock = 0 +}; + +LRUCache.prototype.get = function(key) { + this.clock += 1 + if (this.caches.contains((cache) => cache.key === key)) { + const cache = this.caches.remove((cache) => cache.key === key)[0] + this.caches.enqueue({ + key: key, + value: cache.value, + clock: this.clock, + }) + return cache.value + } + return -1 +}; + +LRUCache.prototype.put = function(key, value) { + this.clock += 1 + if (this.caches.contains((cache) => cache.key === key)) { + const cache = this.caches.remove((cache) => cache.key === key)[0] + this.caches.enqueue({ + key: key, + value: value, + clock: this.clock, + }) + return + } + while (this.caches.size() >= this.capacity) { + this.caches.dequeue() + } + this.caches.enqueue({ + key: key, + value: value, + clock: this.clock, + }) +}; ``` ## STEP2