|
4 | 4 | import java.util.LinkedHashMap;
|
5 | 5 | import java.util.Map;
|
6 | 6 |
|
7 |
| -/** |
8 |
| - * 146. LRU Cache |
9 |
| - * <p> |
10 |
| - * Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. |
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 |
| - |
34 | 7 | public class _146 {
|
35 | 8 |
|
36 | 9 | public class Solution1 {
|
@@ -71,6 +44,8 @@ public class Solution2 {
|
71 | 44 | public class LRUCache {
|
72 | 45 | /**
|
73 | 46 | * The more verbose solution is to implement a doubly linked list yourself plus a map, i.e. LinkedHashMap.
|
| 47 | + * It's very straightforward to implement this, key notes here: https://docs.google.com/spreadsheets/d/1anN6L5OLhUFd1ANtqDdYY6tz2Ao2H1GESfpDiCfeWyM/edit#gid=0 |
| 48 | + * (search for the URL of this problem to find it.) |
74 | 49 | */
|
75 | 50 | private class Node {
|
76 | 51 | int key;
|
@@ -110,11 +85,10 @@ public LRUCache(int capacity) {
|
110 | 85 |
|
111 | 86 | public int get(int key) {
|
112 | 87 | LRUCache.Node node = map.get(key);
|
113 |
| - // HashMap allows value to be null, this is superior than HashTable! |
| 88 | + // HashMap allows value to be null, this is superior to HashTable! |
114 | 89 | if (node == null) {
|
115 | 90 | return -1;
|
116 | 91 | } else {
|
117 |
| - |
118 | 92 | /**Do two operations: this makes the process more clear:
|
119 | 93 | * remove the old node first, and then
|
120 | 94 | * just add the node again.
|
|
0 commit comments