-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlru.java
More file actions
93 lines (93 loc) · 1.94 KB
/
lru.java
File metadata and controls
93 lines (93 loc) · 1.94 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class LRU{
static class Node{
public int key;
public int val;
public Node next;
public Node prev;
public Node(int k,int v){
this.key = k;
this.v = v;
}
}
static class DoubleList{
private Node head;
private Node tail;
private int size;
public DoubleList(){
head = new Node(0,0);
tail = new Node(0,0);
head.next = tail;
tail.prev = head;
size = 0;
}
public void addLast(Node x){
x.prev = tail.prev;
x.next = tail;
tail.prev.next = x;
tail.prev = x;
size++;
}
public void remove(Node x){
x.prev.next = x.next;
x.next.prev = x.prev;
size--;
}
public Node removeFirst(){
if(head.next == tail) return null;
Node first = head.next;
remove(first);
return first;
}
public int size(){
return size;
}
}
static class LRUCache{
private HashMap<Integer,Node> map;
private DoubleList cache;
private int cap;
public LRUCache(int capacity){
this.cap = capacity;
map = new HashMap<>();
cache = new DoubleList();
}
// 将某一个key提升为最近最常使用的key
private void makeRecently(int key){
Node x = map.get(key);
cache.remove(x);
cache.addLast(x);
}
// 添加最近使用的元素
private void addRecently(int key,int val){
Node x = new Node(key,val);
cache.addLast(x);
map.put(key,x);
}
// 删除某一个key
private void seleteKey(int key){
Node x = map.get(key);
cache.remove(x);
map.remove(key);
}
// 删除最久未使用的元素
private void removeLeastRecently(){
Node deletedNode = cache.removeFirst();
int deletedKey = deletedNode.key;
map.remove(deletedKey);
}
public int get(int key){
if(!map.containsKey(key)) return -1;
makeRecently(key);
return map.get(key).val;
}
public void put(int key, int val){
if(map.containsKey(key)){
deletedKey(key);
addRecently(key,val);
return;
}
if(cap == cache.size()) removeLeastRecently();
addRecently(key,val);
}
}
}