LeetCode460. LFU缓存

460. LFU缓存 题目链接

解题思路:哈希表+优先队列

Map<Integer, Node> cache 存储缓存 key、value,PriorityQueue freQueue 按使用频率和最近使用时间降序存储缓存元素,static int timer 计数表示每个元素的使用时间,int capacity 记录缓存的容量

put 元素时,判断是否已存在:存在则更新使用频率和最近使用时间;不存在,则判断是否缓存空间已慢,已满则移除 freQueue 堆顶元素,同时更新 freQueue、cache,未满则直接在 freQueue、cache 中插入元素

get 元素时,判断 cache 是否存在 key,不存在则直接返回 -1;存在则更新使用频率和最近使用时间,返回 value。

参考:https://leetcode.com/problems/lfu-cache/discuss/537093/Java-HashMap%2BPriorityQueue

class LFUCache {

    Map<Integer, Node> cache;
    // 存储每个频率对应的双向链表
    private PriorityQueue<Node> freQueue;
    private static int timer;
    int capacity;
    class Node{
        int key;
        int value;
        int count;
        int timer;
		
		public Node(int key, int value, int count, int timer) {
            this.key = key;
            this.value = value;
            this.count = count;
            this.timer = timer;
        }
    }
    /**
     * 最少使用淘汰算法
     */
    public LFUCache(int capacity) {
        this.capacity = capacity;
        freQueue = new PriorityQueue<>(((o1, o2) ->
                (o1.count == o2.count ? o1.timer - o2.timer : o1.count - o2.count)));
        cache = new HashMap<>();
        timer = 0;
    }

    public int get(int key) {
        if (cache.containsKey(key)) {
            Node node = cache.get(key);
            remove(node);
            add(new Node(node.key, node.value, node.count + 1, timer++));
            return node.value;
        } else {
            return -1;
        } 
    }

    private void remove(Node node) {
        cache.remove(node.key);
        freQueue.remove(node);
    }

    private void add(Node node) {
        cache.put(node.key, node);
        freQueue.offer(node);
    }
    public void put(int key, int value) {
        if (cache.containsKey(key)) {
            Node node = cache.get(key);
            remove(node);
            add(new Node(node.key, value, node.count + 1, timer++));
        } else {
            if (capacity != 0) {
                if (cache.size() == capacity) {
                    remove(freQueue.peek());
                }
                add(new Node(key, value, 1, timer++));
            }
        }                 
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值