-
Notifications
You must be signed in to change notification settings - Fork 5
/
460. LFU Cache.java
106 lines (89 loc) · 2.62 KB
/
460. LFU Cache.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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
import java.util.*;
public class LFUCache {
private class Node {
int key, value, freq;
Node prev, next;
Node(int key, int value) {
this.key = key;
this.value = value;
this.freq = 1;
}
}
private class DoublyLinkedList {
Node head, tail;
int size;
DoublyLinkedList() {
head = new Node(0, 0);
tail = new Node(0, 0);
head.next = tail;
tail.prev = head;
size = 0;
}
void addFirst(Node node) {
Node next = head.next;
head.next = node;
node.prev = head;
node.next = next;
next.prev = node;
size++;
}
void remove(Node node) {
Node prev = node.prev;
Node next = node.next;
prev.next = next;
next.prev = prev;
size--;
}
Node removeLast() {
if (size > 0) {
Node last = tail.prev;
remove(last);
return last;
}
return null;
}
}
private int capacity, minFreq;
private Map<Integer, Node> nodeMap;
private Map<Integer, DoublyLinkedList> freqMap;
public LFUCache(int capacity) {
this.capacity = capacity;
this.minFreq = 0;
this.nodeMap = new HashMap<>();
this.freqMap = new HashMap<>();
}
public int get(int key) {
if (!nodeMap.containsKey(key)) return -1;
Node node = nodeMap.get(key);
update(node);
return node.value;
}
public void put(int key, int value) {
if (capacity == 0) return;
if (nodeMap.containsKey(key)) {
Node node = nodeMap.get(key);
node.value = value;
update(node);
} else {
if (nodeMap.size() == capacity) {
DoublyLinkedList minList = freqMap.get(minFreq);
Node evict = minList.removeLast();
nodeMap.remove(evict.key);
}
Node newNode = new Node(key, value);
nodeMap.put(key, newNode);
minFreq = 1;
freqMap.computeIfAbsent(1, k -> new DoublyLinkedList()).addFirst(newNode);
}
}
private void update(Node node) {
int oldFreq = node.freq;
DoublyLinkedList oldList = freqMap.get(oldFreq);
oldList.remove(node);
if (oldFreq == minFreq && oldList.size == 0) {
minFreq++;
}
node.freq++;
freqMap.computeIfAbsent(node.freq, k -> new DoublyLinkedList()).addFirst(node);
}
}