Skip to content

Commit 5aacecf

Browse files
Time: 715 ms (85.63%), Space: 96 MB (96.41%) - LeetHub
1 parent 77a1712 commit 5aacecf

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

0146-lru-cache/0146-lru-cache.ts

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class LRUCache {
2+
capacity: number;
3+
map: Map<number, number>;
4+
5+
constructor(capacity: number) {
6+
this.capacity = capacity;
7+
this.map = new Map();
8+
}
9+
10+
get(key: number): number {
11+
const value = this.map.get(key);
12+
13+
if (value === undefined) return -1;
14+
15+
// Small hack to re-order keys: we remove the requested key and place it at the end
16+
this.map.delete(key);
17+
this.map.set(key, value);
18+
19+
return value;
20+
}
21+
22+
put(key: number, value: number): void {
23+
// remove last element to avoid overflow, only if it does not have
24+
// the inserted key is a new key
25+
if (this.map.size >= this.capacity && !this.map.has(key)) {
26+
const firstKey = this.map.keys().next().value;
27+
this.map.delete(firstKey);
28+
}
29+
30+
// Small hack to re-order keys: we remove the requested key and place it at the end
31+
this.map.delete(key);
32+
this.map.set(key, value);
33+
}
34+
}
35+
36+
/**
37+
* Your LRUCache object will be instantiated and called as such:
38+
* var obj = new LRUCache(capacity)
39+
* var param_1 = obj.get(key)
40+
* obj.put(key,value)
41+
*/

0 commit comments

Comments
 (0)