LFU 缓存

113 阅读3分钟

1、题目描述(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) 的平均时间复杂度运行。

2、思路

  1. 由题目可知可以用二叉平衡树(TreeMap | TreeSet)来维护键值的使用频数和使用时间,所以我们建立的节点就要有可比较性。所以我们要重写 hashCode()、equals()、compareTo()方法。
class Node implements Comparable<Node> {
    int count;
    int time;
    int key;
    int value;
    Node(int count, int time, int key, int value) {
        this.count = count;
        this.time = time;
        this.key = key;
        this.value = value;
    }
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof Node) {
            Node node = (Node) obj;
            return this.count == node.count && this.time == node.time;
        }
        return false;
    }
    public int compareTo(Node node) {
        return count == node.count ? time - node.time : count - node.count;
    }
    public int hashCode() {
        return count * 1000000007 + time;
    }
}
  1. 对于 get() 方法,当所查询的键不在时直接返回 -1,当查询的键在时,从哈希表中获取并更新键的使用频数。
  2. 对于 put() 方法,当插入的键不在时分为两种情况。一、键的数量不大于最大容量时,直接插入即可;二、键的数量等于最大容量时,移除最久未使用且使用频数最低的键,然后插入新的键值对。当插入的键已经存在时,就要同时更新键的使用频数和键对应的值。
  3. TreeSet 的用到的几个接口
Comparator comparator():返回当前Set使用的Comparator,若返回null,表示以自然顺序排序。
Object first() 返回此 set 中当前第一个(最低)元素。
Object last() 返回此 set 中当前最后一个(最高)元素。

3、代码 & 注释

    int capacity;
    int time;
    Map<Integer, Node> map;
    TreeSet<Node> treeSet;

    public LFUCache(int capacity) {
        this.capacity = capacity;
        this.time = 0;
        map = new HashMap<Integer, Node>();
        treeSet = new TreeSet<Node>();
    }
    
    public int get(int key) {
        if (capacity == 0 || !map.containsKey(key)) return -1;
        // 获取旧的缓存
        Node cache = map.get(key);
        // 从平衡二叉树中删除旧的缓存
        treeSet.remove(cache);
        // 将旧缓存更新
        cache.count += 1;
        cache.time = time++ + 1;
        // 将新缓存重新放入哈希表和平衡二叉树中
        treeSet.add(cache);
        map.put(key, cache);
        return cache.value;
    }
    
    public void put(int key, int value) {
        if (capacity == 0) return;
        if (!map.containsKey(key)) {
            // 达到最大容量
            if (map.size() == capacity) {
                // 从哈希表和平衡二叉树中删除最近最少使用的缓存
                treeSet.remove(treeSet.first().key);
                treeSet.remove(treeSet.first());
            }
            // 创建新的缓存
            Node cache = new Node(1, ++time, key, value);
            // 将新缓存放入哈希表和平衡二叉树中
            map.put(key, cache);
            treeSet.add(cache);
        } else {
            Node cache = map.get(key);
            treeSet.remove(cache);
            cache.count += 1;
            cache.time = time++ + 1;
            cache.value = value;
            treeSet.add(cache);
            map.put(key, cache);
        }
    }