LeetCode_数据结构设计_困难_460. LFU 缓存

x33g5p2x  于2022-05-11 转载在 其他  
字(3.6k)|赞(0)|评价(0)|浏览(292)

1.题目

请你为最不经常使用(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

提示:
0 <= capacity <= 104
0 <= key <= 105
0 <= value <= 109
最多调用 2 * 105 次 get 和 put 方法

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lfu-cache

2.思路

(1)数据结构设计
思路参考算法题就像搭乐高:手把手带你拆解 LFU 算法

3.代码实现(Java)

//思路1————数据结构设计
class LFUCache {

    //LFU 缓存的最大容量
    int capacity;
    //LFU 缓存最小的频次
    int minFreq;
    //key 到 value 的映射
    HashMap<Integer, Integer> keyToValue;
    //key 到 freq 的映射
    HashMap<Integer, Integer> keyToFreq;
    //freq 到 key 列表的映射
    HashMap<Integer, LinkedHashSet<Integer>> freqToKeys;

    public LFUCache(int capacity) {
        //初始化
        this.capacity = capacity;
        this.minFreq = 0;
        this.keyToValue = new HashMap<>();
        this.keyToFreq = new HashMap<>();
        this.freqToKeys = new HashMap<>();
    }
    
    public int get(int key) {
        if (keyToValue.containsKey(key) == false) {
            //未找到该 key
            return -1;
        } else {
            //找到该 key,则其频率加一
            increaseFreq(key);
            return keyToValue.get(key);
        }
    }
    
    public void put(int key, int value) {
        if (this.capacity <= 0) {
            return;
        }       
        if (keyToValue.containsKey(key)) {
            /*若 key 已存在,修改其对应的 value 即可*/
            keyToValue.put(key, value);
            //key 的频率加一
            increaseFreq(key);
            return;
        } 
        /*若 key 不存在,则需要将其插入*/
        if (this.capacity <= keyToValue.size()) {
            //LFU 缓存容量已满,则需要淘汰一个 freq 最小的 key
            removeMinFreqKey();
        } 
        //将 (key, value) 加入到 keyToValue 中
        keyToValue.put(key, value);
        //将 (key, 1) 加入到 keyToFreq 中
        keyToFreq.put(key, 1);
        //更新 freqToKeys
        freqToKeys.putIfAbsent(1, new LinkedHashSet<>());
        freqToKeys.get(1).add(key);
        //插入新 key 后 minFreq 肯定是 1
        this.minFreq = 1;
    }

    //key的频率加一
    public void increaseFreq(int key) {
        //更新 keyToFreq
        int freq = keyToFreq.get(key);
        keyToFreq.put(key, freq + 1);
        //将 key 从 freq 对应的列表中删除
        freqToKeys.get(freq).remove(key);
        //将 key 加入 freq + 1 对应的列表中
        freqToKeys.putIfAbsent(freq + 1, new LinkedHashSet<>());
        freqToKeys.get(freq + 1).add(key);
        //如果 freq 对应的列表为空,则移除这个 freq
        if (freqToKeys.get(freq).isEmpty()) {
            freqToKeys.remove(freq);
            //如果这个 freq 恰好是 minFreq,则更新 minFreq
            if (freq == this.minFreq) {
                this.minFreq++;
            }
        }
    }

    //淘汰一个 freq 最小的 key
    public void removeMinFreqKey() {
        //从 freqToKeys 中找到 freq = minFreq 的列表‘
        LinkedHashSet<Integer> keysList = freqToKeys.get(this.minFreq);
        //keysList 中最先加入的 key 就是应该被淘汰的 key
        int removedKey = keysList.iterator().next();
        keysList.remove(removedKey);
        if (keysList.isEmpty()) {
            //删除 removedKey 后,keysList 为空
            freqToKeys.remove(this.minFreq);
            /*
                此处不需要更新 minFreq,具体原因如下:
                removeMinFreqKey() 在 put() 中插入新 key 时可能会调用,而 put() 的代码中,
                插入新 key 时一定会把 minFreq 更新成 1,所以此处无需更新 minFreq            
            */
        }
        //删除 keyToValue 中的 removedKey
        keyToValue.remove(removedKey);
        //删除 keyToFreq 中的 removedKey
        keyToFreq.remove(removedKey);
    }
}

/**
 * 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);
 */

相关文章

微信公众号

最新文章

更多