LFU 缓存
描述
-
请你为 最不经常使用(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) 的平均时间复杂度运行
示例:
输入:
["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
输出:
[null, null, null, 1, null, -1, 3, null, -1, 3, 4]
解释:
// cnt(x) = 键 x 的使用计数
// cache=[] 将显示最后一次使用的顺序(最左边的元素是最近的)
LFUCache lfu = new LFUCache(2);
lfu.put(1, 1); // cache=[1,_], cnt(1)=1
lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1
lfu.get(1); // 返回 1
// cache=[1,2], cnt(2)=1, cnt(1)=2
lfu.put(3, 3); // 去除键 2 ,因为 cnt(2)=1 ,使用计数最小
// cache=[3,1], cnt(3)=1, cnt(1)=2
lfu.get(2); // 返回 -1(未找到)
lfu.get(3); // 返回 3
// cache=[3,1], cnt(3)=2, cnt(1)=2
lfu.put(4, 4); // 去除键 1 ,1 和 3 的 cnt 相同,但 1 最久未使用
// cache=[4,3], cnt(4)=1, cnt(3)=2
lfu.get(1); // 返回 -1(未找到)
lfu.get(3); // 返回 3
// cache=[3,4], cnt(4)=1, cnt(3)=3
lfu.get(4); // 返回 4
// cache=[3,4], cnt(4)=2, cnt(3)=3
提示
- 1 <= capacity <= 1 0 4 10^4 104
- 0 <= key <= 1 0 5 10^5 105
- 0 <= value <= 1 0 9 10^9 109
- 最多调用 2 * 1 0 5 10^5 105 次 get 和 put 方法
Typescript 版算法实现
1 ) 方案1: 哈希表 + 平衡二叉树
class Node {
cnt: number;
time: number;
key: number;
value: number;
constructor(cnt: number, time: number, key: number, value: number) {
this.cnt = cnt;
this.time = time;
this.key = key;
this.value = value;
}
static compare(a: Node, b: Node): number {
if (a.cnt === b.cnt) {
return a.time - b.time;
}
return a.cnt - b.cnt;
}
}
class LFUCache {
private capacity: number;
private time: number;
private keyTable: Map<number, Node>;
private nodeSet: Set<Node>;
constructor(capacity: number) {
this.capacity = capacity;
this.time = 0;
this.keyTable = new Map<number, Node>();
this.nodeSet = new Set<Node>();
}
private removeNode(node: Node): void {
const toRemove = [...this.nodeSet].find(n => n.key === node.key);
if (toRemove) {
this.nodeSet.delete(toRemove);
}
}
private addNode(node: Node): void {
this.removeNode(node); // Ensure uniqueness based on key
this.nodeSet.add(node);
}
get(key: number): number {
if (this.capacity === 0 || !this.keyTable.has(key)) {
return -1;
}
const cache = this.keyTable.get(key)!;
this.removeNode(cache);
cache.cnt += 1;
cache.time = ++this.time;
this.addNode(cache);
this.keyTable.set(key, cache);
return cache.value;
}
put(key: number, value: number): void {
if (this.capacity === 0) {
return;
}
if (!this.keyTable.has(key)) {
if (this.keyTable.size === this.capacity) {
// Remove the least frequently used item
const lfuNode = [...this.nodeSet].sort(Node.compare)[0];
if (lfuNode) {
this.keyTable.delete(lfuNode.key);
this.removeNode(lfuNode);
}
}
const newNode = new Node(1, ++this.time, key, value);
this.keyTable.set(key, newNode);
this.addNode(newNode);
} else {
const cache = this.keyTable.get(key)!;
this.removeNode(cache);
cache.cnt += 1;
cache.time = ++this.time;
cache.value = value;
this.addNode(cache);
this.keyTable.set(key, cache);
}
}
}
/**
* Your LFUCache object will be instantiated and called as such:
* var obj = new LFUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
- 超出时间限制
2 ) 方案2:双哈希表 + 双向链表
class Node {
key: number;
val: number;
freq: number;
prev?: Node | null;
next?: Node | null;
constructor(key: number, val: number, freq: number = 1) {
this.key = key;
this.val = val;
this.freq = freq;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList {
head: Node;
tail: Node;
constructor() {
this.head = new Node(0, 0);
this.tail = new Node(0, 0);
this.head.next = this.tail;
this.tail.prev = this.head;
}
pushFront(node: Node): void {
node.prev = this.head;
node.next = this.head.next;
if (this.head.next) {
this.head.next.prev = node;
}
this.head.next = node;
}
remove(node: Node): void {
if (node.prev && node.next) {
node.prev.next = node.next;
node.next.prev = node.prev;
node.next = null;
node.prev = null;
}
}
removeBack(): Node | null {
if (this.tail.prev === this.head) return null;
const last = this.tail.prev!;
this.remove(last);
return last;
}
isEmpty(): boolean {
return this.head.next === this.tail;
}
}
class LFUCache {
private cache: Map<number, Node>;
private freqMap: Map<number, DoublyLinkedList>;
private minFreq: number;
private capacity: number;
constructor(capacity: number) {
this.capacity = capacity;
this.cache = new Map<number, Node>();
this.freqMap = new Map<number, DoublyLinkedList>();
this.minFreq = 0;
}
get(key: number): number {
if (this.capacity === 0 || !this.cache.has(key)) return -1;
const node = this.cache.get(key)!;
this.incrFreq(node);
return node.val;
}
put(key: number, value: number): void {
if (this.capacity === 0) return;
if (this.cache.has(key)) {
const node = this.cache.get(key)!;
node.val = value;
this.incrFreq(node);
} else {
if (this.cache.size === this.capacity) {
const lfuList = this.freqMap.get(this.minFreq)!;
const removedNode = lfuList.removeBack();
if (removedNode) {
this.cache.delete(removedNode.key);
}
}
const newNode = new Node(key, value);
this.addNode(newNode);
this.cache.set(key, newNode);
this.minFreq = 1;
}
}
private incrFreq(node: Node): void {
const list = this.freqMap.get(node.freq)!;
list.remove(node);
if (list.isEmpty()) {
this.freqMap.delete(node.freq);
if (node.freq === this.minFreq) {
this.minFreq++;
}
}
node.freq++;
this.addNode(node);
}
private addNode(node: Node): void {
let list = this.freqMap.get(node.freq);
if (!list) {
list = new DoublyLinkedList();
this.freqMap.set(node.freq, list);
}
list.pushFront(node);
}
}
/**
* Your LFUCache object will be instantiated and called as such:
* var obj = new LFUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
3 ) 方案3:map + set
class LFUCache {
size: number;
values: Map<number, number> = new Map();
times: Map<number, number> = new Map();
useMap: Map<number, Set<number>> = new Map();
min: number;
constructor(capacity: number) {
// 缓存空间大小
this.size = capacity;
// 缓存存储
this.values = new Map(); // key:value
this.times = new Map(); // key:次数
// 找到当前次数最小的key
// useMap更新的逻辑,其实vue的响应式依赖管理很像
this.useMap = new Map(); //次数:key,set(key)
this.min = 0; //最小次数是多少
}
get(key: number): number {
if (this.values.has(key)) {
// 更新计数
this.updateCount(key);
return this.values.get(key);
}
return -1;
}
put(key: number, value: number): void {
//缓存空间为0,不操作
if (this.size === 0) return;
if (this.values.has(key)) {
// key值存在,不需要淘汰
this.values.set(key, value);
this.updateCount(key);
} else {
// key值不存在,判断是否超过缓存 size
if (this.size === this.values.size) {
// 满了需要淘汰掉次数最少的、最长时间未访问的
let minSet = this.useMap.get(this.min);
let minKey = minSet.keys().next().value;
minSet.delete(minKey);
this.values.delete(minKey);
this.times.delete(minKey);
}
// 加入缓存
this.values.set(key, value);
// 这个数据出现了1次
let useSet = this.useMap.get(1) || (new Set() as Set<number>);
useSet.add(key);
this.useMap.set(1, useSet);
this.times.set(key, 1);
this.min = 1;
}
}
updateCount(key: number): void {
let time = this.times.get(key);
let useSet = this.useMap.get(time);
if (this.min === time && useSet.size === 1) {
// 当前次数是最小值并且这个次数set集合只有一个 key
this.min += 1;
}
time += 1;
useSet.delete(key);
useSet = this.useMap.get(time) || new Set();
useSet.add(key);
this.useMap.set(time, useSet);
this.times.set(key, time);
}
}
/**
* Your LFUCache object will be instantiated and called as such:
* var obj = new LFUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
355



被折叠的 条评论
为什么被折叠?



