题解 | 设计LFU缓存结构

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * lfu design
     * @param operators int整型二维数组 ops
     * @param k int整型 the k
     * @return int整型一维数组
     */
    int time = 0;

    PriorityQueue<Node> pq = new PriorityQueue<Node>(new Comparator<Node>() {
        public int compare(Node n1, Node n2) {
            if (n1.count == n2.count) return n1.time - n2.time;
            return n1.count - n2.count;
        }
    });

    Map<Integer, Node> cache = new HashMap<>();

    class Node {
        int key;
        int val;
        int count;
        int time;

        Node(int key, int val, int time) {
            this.key = key;
            this.val = val;
            this.count = 1;
            this.time = time;
        }
    }

    public int[] LFU (int[][] operators, int k) {
        // write code here
        List<Integer> list = new ArrayList<>();
        for (int[] op : operators) {
            int a = op[0];
            if (a == 1){
                int key = op[1];
                int val = op[2];
                set(key, val, k);
            } else {
                int key = op[1];
                int val = get(key);
                list.add(val);
            }
        }
        int[] ans = new int[list.size()];
        int i = 0;
        for (int num : list) {
            ans[i++] = num;
        }
        return ans;
    }

    private void set(int key, int val, int k) {
        if (cache.containsKey(key)) {
            // 更新 value
            Node node = cache.get(key);
            pq.remove(node);
            node.count++;
            node.time = time++;
            node.val = val;

            pq.offer(node);
            
            return;
        } else {
            Node node = new Node(key, val, time++);
            cache.put(key, node);
            if (pq.size() < k) {
                pq.offer(node);
            } else {
                Node peek = pq.poll(); // 去掉一个
                //System.out.println(peek.key  + " " + peek.count + " " + peek.time);
                cache.remove(peek.key);
                pq.offer(node);
            }
        }
    }


    private int get(int key) {
        if (!cache.containsKey(key)) return -1;
        Node node = cache.get(key);
        pq.remove(node);
        node.count++;
        node.time = time++;
        pq.offer(node);
        return node.val;
    }
}

全部评论

相关推荐

06-27 18:45
中山大学 Ruby
25届应届毕业生,来广州2个礼拜了,找不到工作,绝望了,太难过了…
应届想染班味:9爷找不到工作只能说明,太摆了或者太挑了。
点赞 评论 收藏
分享
07-02 13:50
闽江学院 Java
点赞 评论 收藏
分享
05-09 12:23
已编辑
华南理工大学 Java
野猪不是猪🐗:给他装的,双九+有实习的能看的上这种厂我直接吃⑨✌们拿它练练面试愣是给他整出幻觉了
点赞 评论 收藏
分享
机械打工仔:有说的你怀疑一下就行了,直接问也太实诚了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-01 17:13
想去,但是听说加班强度实在难崩,所以拒绝了,现在有点心梗对面hr感觉也是实习生,打电话的时候怪紧张的,但是感觉人很好嘞
水中水之下水道的鼠鼠:哥们这不先去体验一下,不行再跑呗,大不了混个实习经历(有更好的转正offer就当我没说)
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务