Skip to content

Commit d621f10

Browse files
committed
Add solution #146
1 parent 9f21ddb commit d621f10

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@
126126
143|[Reorder List](./0143-reorder-list.js)|Medium|
127127
144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy|
128128
145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy|
129+
146|[LRU Cache](./0146-lru-cache.js)|Medium|
129130
148|[Sort List](./0148-sort-list.js)|Medium|
130131
149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard|
131132
151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium|

solutions/0146-lru-cache.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* 146. LRU Cache
3+
* https://leetcode.com/problems/lru-cache/
4+
* Difficulty: Medium
5+
*
6+
* Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
7+
*
8+
* Implement the LRUCache class:
9+
* - LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
10+
* - int get(int key) Return the value of the key if the key exists, otherwise return -1.
11+
* - void put(int key, int value) Update the value of the key if the key exists. Otherwise,
12+
* add the key-value pair to the cache. If the number of keys exceeds the capacity from
13+
* this operation, evict the least recently used key.
14+
*
15+
* The functions get and put must each run in O(1) average time complexity.
16+
*/
17+
18+
/**
19+
* @param {number} capacity
20+
*/
21+
var LRUCache = function(capacity) {
22+
this.cache = new Map();
23+
this.capacity = capacity;
24+
};
25+
26+
/**
27+
* @param {number} key
28+
* @return {number}
29+
*/
30+
LRUCache.prototype.get = function(key) {
31+
if (!this.cache.has(key)) {
32+
return -1;
33+
}
34+
35+
const value = this.cache.get(key);
36+
this.cache.delete(key);
37+
this.cache.set(key, value);
38+
return this.cache.get(key);
39+
};
40+
41+
/**
42+
* @param {number} key
43+
* @param {number} value
44+
* @return {void}
45+
*/
46+
LRUCache.prototype.put = function(key, value) {
47+
if (this.cache.has(key)) {
48+
this.cache.delete(key);
49+
}
50+
this.cache.set(key, value);
51+
if (this.cache.size > this.capacity) {
52+
this.cache.delete(this.cache.keys().next().value);
53+
}
54+
};

0 commit comments

Comments
 (0)