请你为 最不经常使用(LFU)缓存算法设计并实现数据结构。
实现 LFUCache 类:
LFUCache(int capacity) - 用数据结构的容量 capacity 初始化对象
int get(int key) - 如果键 key 存在于缓存中,则获取键的值,否则返回 -1 。
void put(int key, int value) - 如果键 key 已存在,则变更其值;如果键不存在,请插入键值对。当缓存达到其容量 capacity 时,则应该在插入新项之前,移除最不经常使用的项。在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,应该去除 最近最久未使用 的键。
为了确定最不常使用的键,可以为缓存中的每个键维护一个 使用计数器 。使用计数最小的键是最久未使用的键。
当一个键首次插入到缓存中时,它的使用计数器被设置为 1 (由于 put 操作)。对缓存中的键执行 get 或 put 操作,使用计数器的值将会递增。
函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。
挑一种实现方式来说吧,使用哈希表+平衡二叉树来实现.创建一个Node节点的类,用于存放key,value,以及时间time和使用频率frequency
其实真的也没有什么特别难的,就是理解了整个设计流程即可
//使用哈希表+平衡二叉树
class LFU {
//缓存容量和时间戳
int capacity, time;
HashMap<Integer, Node> map;
TreeSet<Node> set;
public LFU(int capacity) {
this.capacity = capacity;
this.time = 0;
map = new HashMap<>();
set = new TreeSet<>();
}
public int get(int key) {
if (capacity == 0) return -1;
//如果哈希表中没有键key返回-1
Node node = map.get(key);
if (node == null) return -1;
//从平衡二叉树中删除旧的缓存
set.remove(node);
//将旧缓存更新
node.frequent++;
node.time = ++time;//将时间更新
//将新缓存重新放入哈希表和平衡二叉树中
set.add(node);
map.put(key, node);
return node.value;
}
public void put(int key, int value) {
if (capacity == 0) return;
if (!map.containsKey(key)) {
//如果到达缓存容量上限
if (map.size() == capacity) {
//从哈希表和平衡二叉树中删除最近最少使用的缓存
map.remove(set.first().key);
set.remove(set.first());
}
//创建新的缓存
Node node = new Node(key, value, ++time, 1);
//将新缓存放入哈希表和平衡二叉树中
map.put(key, node);
set.add(node);
} else {
//和get时候类似
Node node = map.get(key);
set.remove(node);
node.frequent++;
node.time = ++time;
node.value = value;//这一步千万别忘了 要更新value值!!!!
set.add(node);
map.put(key, node);
}
}
}
//定义平衡二叉树的节点 并且自定义排序规则
class Node implements Comparable<Node> {
int key, value, time, frequent;
public Node(int key, int value, int time, int frequent) {
this.key = key;
this.value = value;
this.time = time;
this.frequent = frequent;
}
//两个节点相等的判断 只需要时间和使用频率相同即可
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node node = (Node) o;
return time == node.time && frequent == node.frequent;
}
@Override
public int hashCode() {
return Objects.hash(key, value, time, frequent);
}
//比较的规则是先按使用频率 再按时间前后
@Override
public int compareTo(Node o) {
return frequent == o.frequent ? this.time - o.time : frequent - o.frequent;
}
}