460. LFU 缓存
请你为 最不经常使用(LFU)缓存算法设计并实现数据结构。
实现 LFUCache 类:
LFUCache(int capacity) - 用数据结构的容量 capacity 初始化对象
int get(int key) - 如果键存在于缓存中,则获取键的值,否则返回 -1。
void put(int key, int value) - 如果键已存在,则变更其值;如果键不存在,请插入键值对。当缓存达到其容量时,则应该在插入新项之前,使最不经常使用的项无效。在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,应该去除 最近最久未使用 的键。
注意「项的使用次数」就是自插入该项以来对其调用 get 和 put 函数的次数之和。使用次数会在对应项被移除后置为 0 。
为了确定最不常使用的键,可以为缓存中的每个键维护一个 使用计数器 。使用计数最小的键是最久未使用的键。
当一个键首次插入到缓存中时,它的使用计数器被设置为 1 (由于 put 操作)。对缓存中的键执行 get 或 put 操作,使用计数器的值将会递增。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lfu-cache
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
class LFUCache {
private int capacity;
private int minFreq;
private Map<Integer, Node> keyMap;
private Map<Integer, LinkedList<Node>> freqMap;
public LFUCache(int capacity) {
this.capacity = capacity;
this.minFreq = 0;
this.keyMap = new HashMap<>();
this.freqMap = new HashMap<>();
}
public int get(int key) {
Node node = keyMap.get(key);
if (node == null) {
return -1;
}
LinkedList<Node> nodes = freqMap.get(node.freq);
if (nodes.size() == 1) {
freqMap.remove(node.freq);
if (minFreq == node.freq) {
minFreq++;
}
} else {
nodes.remove(node);
}
freqMap.computeIfAbsent(++node.freq, k -> new LinkedList<>()).offerFirst(node);
return node.value;
}
public void put(int key, int value) {
if (capacity == 0) {
return;
}
Node node = keyMap.get(key);
if (node == null) {
if (keyMap.size() == capacity) {
LinkedList<Node> nodes = freqMap.get(minFreq);
keyMap.remove(nodes.pollLast().key);
if (nodes.size() == 0) {
freqMap.remove(minFreq);
}
}
minFreq = 1;
node = new Node(key, value, 1);
keyMap.put(key, node);
freqMap.computeIfAbsent(node.freq, k -> new LinkedList<>()).offerFirst(node);
} else {
node.value = value;
LinkedList<Node> nodes = freqMap.get(node.freq);
if (nodes.size() == 1) {
freqMap.remove(node.freq);
if (minFreq == node.freq) {
minFreq++;
}
} else {
nodes.remove(node);
}
freqMap.computeIfAbsent(++node.freq, k -> new LinkedList<>()).offerFirst(node);
}
}
}
class Node {
int key;
int value;
int freq;
public Node(int key, int value, int freq) {
this.key = key;
this.value = value;
this.freq = freq;
}
}
/**
* Your LFUCache object will be instantiated and called as such:
* LFUCache obj = new LFUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
心之所向,素履以往 生如逆旅,一苇以航