Skip to content

Commit 0720d92

Browse files
author
Tushar Borole
committed
146. LRU Cache
1 parent 4104388 commit 0720d92

File tree

3 files changed

+62
-13
lines changed

3 files changed

+62
-13
lines changed

.idea/workspace.xml

Lines changed: 13 additions & 13 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@
9393
| 24 | [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) | [Recursive](swap_nodes_in_pairs.js) | 68 ms | 34 MB | Medium | O(N) | | [:link:](https://www.youtube.com/watch?v=zOovxGmION4) |
9494
| 48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | [Iterative](rotate_image.js) | 56 ms | 33.7 MB | Medium | O(N) | O(1) | [:link:](https://leetcode.com/problems/rotate-image/solution/) |
9595
| 36 | [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) | [Itterative](valid_sudoku.js) | 68 ms | 37.7 MB | Medium | O(1) | O(1) | [:link:](https://leetcode.com/problems/valid-sudoku/solution/) |
96+
| 146 | [ LRU Cache](https://leetcode.com/problems/lru-cache/) | [Map](lru_cache.js) | 216 ms | 58.8 MB | Medium | O(1) | O(1) | |
9697
| 340 | [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/) | [Sliding Window Approach](k_distinct_characters.js) | 68 ms | 37.1 MB | Hard | NlogN | | [:link:](https://www.youtube.com/watch?v=MK-NZ4hN7rs&t=1936s) |
9798

9899
## Others

lru_cache.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// https://leetcode.com/problems/lru-cache/
2+
3+
/**
4+
* @param {number} capacity
5+
*/
6+
var LRUCache = function(capacity) {
7+
this.cache = new Map();
8+
this.capacity = capacity;
9+
};
10+
11+
/**
12+
* @param {number} key
13+
* @return {number}
14+
*/
15+
LRUCache.prototype.get = function(key) {
16+
let cache = this.cache;
17+
let temp = cache.get(key);
18+
if (temp) {
19+
// to maintain order
20+
cache.delete(key);
21+
cache.set(key, temp);
22+
return temp;
23+
} else {
24+
return -1;
25+
}
26+
};
27+
28+
/**
29+
* @param {number} key
30+
* @param {number} value
31+
* @return {void}
32+
*/
33+
LRUCache.prototype.put = function(key, value) {
34+
let cache = this.cache;
35+
if (cache.has(key)) {
36+
cache.delete(key);
37+
} else if (cache.size >= this.capacity) {
38+
cache.delete(cache.keys().next().value);
39+
}
40+
cache.set(key, value);
41+
};
42+
43+
/**
44+
* Your LRUCache object will be instantiated and called as such:
45+
* var obj = new LRUCache(capacity)
46+
* var param_1 = obj.get(key)
47+
* obj.put(key,value)
48+
*/

0 commit comments

Comments
 (0)