|
6 | 6 |
|
7 | 7 | /**
|
8 | 8 | * 146. LRU Cache
|
9 |
| - * |
| 9 | + * <p> |
10 | 10 | * Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
|
11 |
| -
|
12 |
| - get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. |
13 |
| - put(key, value) - Set or insert the value if the key is not already present. |
14 |
| - When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. |
15 |
| -
|
16 |
| - Follow up: |
17 |
| - Could you do both operations in O(1) time complexity? |
18 |
| -
|
19 |
| - Example: |
20 |
| -
|
21 |
| - LRUCache cache = new LRUCache(2);//capacity |
22 |
| -
|
23 |
| - cache.put(1, 1); |
24 |
| - cache.put(2, 2); |
25 |
| - cache.get(1); // returns 1 |
26 |
| - cache.put(3, 3); // evicts key 2 |
27 |
| - cache.get(2); // returns -1 (not found) |
28 |
| - cache.put(4, 4); // evicts key 1 |
29 |
| - cache.get(1); // returns -1 (not found) |
30 |
| - cache.get(3); // returns 3 |
31 |
| - cache.get(4); // returns 4 |
32 |
| - */ |
| 11 | + * <p> |
| 12 | + * get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. |
| 13 | + * put(key, value) - Set or insert the value if the key is not already present. |
| 14 | + * When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. |
| 15 | + * <p> |
| 16 | + * Follow up: |
| 17 | + * Could you do both operations in O(1) time complexity? |
| 18 | + * <p> |
| 19 | + * Example: |
| 20 | + * <p> |
| 21 | + * LRUCache cache = new LRUCache(2);//capacity |
| 22 | + * <p> |
| 23 | + * cache.put(1, 1); |
| 24 | + * cache.put(2, 2); |
| 25 | + * cache.get(1); // returns 1 |
| 26 | + * cache.put(3, 3); // evicts key 2 |
| 27 | + * cache.get(2); // returns -1 (not found) |
| 28 | + * cache.put(4, 4); // evicts key 1 |
| 29 | + * cache.get(1); // returns -1 (not found) |
| 30 | + * cache.get(3); // returns 3 |
| 31 | + * cache.get(4); // returns 4 |
| 32 | + */ |
33 | 33 |
|
34 | 34 | public class _146 {
|
35 | 35 |
|
@@ -70,7 +70,7 @@ public void put(int key, int value) {
|
70 | 70 | public class Solution2 {
|
71 | 71 | public class LRUCache {
|
72 | 72 | /**
|
73 |
| - * The more verbose solution is to write a doubly linked list plus a map. |
| 73 | + * The more verbose solution is to implement a doubly linked list yourself plus a map, i.e. LinkedHashMap. |
74 | 74 | */
|
75 | 75 | private class Node {
|
76 | 76 | int key;
|
|
0 commit comments