-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNo460LFUCache.java
More file actions
105 lines (88 loc) · 2.6 KB
/
No460LFUCache.java
File metadata and controls
105 lines (88 loc) · 2.6 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
94
95
96
97
98
99
100
101
102
103
104
105
package com.wzx.leetcode;
import java.util.*;
/**
* @author wzx
* @see <a href="https://leetcode.com/problems/lfu-cache/">https://leetcode.com/problems/lfu-cache/</a>
*/
public class No460LFUCache {
/**
* 维护频率和key的映射关系
*/
private static class FreqMap {
// 使用LinkedHashSet维护相同频率下,key的LRU序列
private final Map<Integer, LinkedHashSet<Integer>> freq2Key;
private final Map<Integer, Integer> key2Freq;
private int minFreq = 0;
public FreqMap() {
freq2Key = new HashMap<>();
key2Freq = new HashMap<>();
}
public void increaseFreq(int key) {
int freq = key2Freq.get(key);
// 删除(key, freq)
freq2Key.get(freq).remove(key);
// 增加(key, freq + 1)
freq2Key.putIfAbsent(freq + 1, new LinkedHashSet<>());
freq2Key.get(freq + 1).add(key);
key2Freq.put(key, freq + 1);
// 更新minFreq
if (freq2Key.get(minFreq).isEmpty()) {
// minFreq对应的key为空, 说明刚刚访问的key对应的就是minFreq
minFreq += 1;
}
}
public int popMinFreqKey() {
int popKey = freq2Key.get(minFreq).iterator().next();
// 删除(key, freq)
freq2Key.get(minFreq).remove(popKey);
if (freq2Key.get(minFreq).isEmpty()) {
// 只有在缓存淘汰时才会调用popMinFreqKey()
// 所以后面一定会添加一个频率为1的新key
minFreq = 0;
}
return popKey;
}
public void addKey(int key) {
key2Freq.put(key, 1);
freq2Key.putIfAbsent(1, new LinkedHashSet<>());
freq2Key.get(1).add(key);
minFreq = 1;
}
}
/**
* 维护key->frequency及其倒排索引, LinkedHashSet维护同一访问频率的LRU序列
* <p>
* time: O(1)
* space: O(n)
*/
public static class LFUCache {
private final Map<Integer, Integer> KVMap;
private final FreqMap freqMap;
private final int capacity;
public LFUCache(int capacity) {
KVMap = new HashMap<>();
freqMap = new FreqMap();
this.capacity = capacity;
}
public int get(int key) {
if (!KVMap.containsKey(key)) return -1;
freqMap.increaseFreq(key);
return KVMap.get(key);
}
public void put(int key, int value) {
if (capacity == 0) return;
if (!KVMap.containsKey(key)) {
// 缓存淘汰
if (KVMap.size() == capacity) {
int popKey = freqMap.popMinFreqKey();
KVMap.remove(popKey);
}
// 添加
freqMap.addKey(key);
} else {
freqMap.increaseFreq(key);
}
KVMap.put(key, value);
}
}
}