-
-
Notifications
You must be signed in to change notification settings - Fork 610
/
LRUCache.java
63 lines (48 loc) · 1.04 KB
/
LRUCache.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package problems.hard;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
/**
* Created by sherxon on 6/17/17.
*/
class ListNode {
public int key;
public int val;
public ListNode(int key, int val) {
this.val = val;
this.key = key;
}
public boolean equals(Object o) {
ListNode ob = (ListNode) o;
return this.key == ob.key;
}
}
public class LRUCache {
LinkedList<ListNode> list = new LinkedList<>();
Map<Integer, ListNode> map = new HashMap<>();
int n = 0;
public LRUCache(int capacity) {
this.n = capacity;
}
public int get(int key) {
ListNode node = map.get(key);
if (node == null) {
return -1;
}
list.remove(node);
list.add(node);
return node.val;
}
public void put(int key, int value) {
ListNode node = new ListNode(key, value);
if (map.containsKey(key)) {
list.remove(node);
}
list.add(node);
if (list.size() > n) {
ListNode old = list.removeFirst();
map.remove(old.key);
}
map.put(key, node);
}
}