题解 | #设计LRU缓存结构#

设计LRU缓存结构

https://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84

import java.util.*;


public class Solution {

    private Map<Integer, ListNode> map = new HashMap<>();
    private ListNode head;
    private ListNode tail;
    private int size;
    private int capacity;

    public Solution(int capacity) {
        // write code here
        this.capacity = capacity;
        this.size = 0;
    }

    public int get(int key) {
        // write code here
        if (!map.containsKey(key)) {
            return -1;
        }
        ListNode node = map.get(key);
        if (node != head) {
            moveToHead(node);
        }

        return node.value;
    }

    public void set(int key, int value) {
        // write code here
        ListNode node = map.get(key);
        if (node != null) {
            node.value = value;
            moveToHead(node);
        } else {
            node = new ListNode(key, value);
            if (size == capacity) {
                // remove tail
                map.remove(tail.key);
                tail = tail.pre;
                tail.next = null;
                this.size--;
            }
            // add to head
            if (head == null) {
                head = node;
                tail = node;
            } else {
                node.next = head;
                head.pre = node;
                head = node;
            }
            map.put(key, node);

            size++;
        }
    }

    

    private void moveToHead(ListNode node) {
        if (node == head) {
            return;
        }
        if (node == tail) {
            tail = node.pre;
            tail.next = null;
        } else {
            ListNode pre = node.pre;
            ListNode next = node.next;
            pre.next = next;
            next.pre = pre;
        }

        node.next = head;
        node.pre = null;
        head.pre = node;
        head = node;
    }

    public static class ListNode {
        public int key;
        public int value;
        public ListNode next;
        public ListNode pre;

        public ListNode(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution solution = new Solution(capacity);
 * int output = solution.get(key);
 * solution.set(key,value);
 */

全部评论

相关推荐

点赞 评论 收藏
分享
09-01 11:31
门头沟学院 Java
buul:七牛云的吧,感觉想法是好的,但是大家没那么多时间弄他这个啊。。。不知道的还以为他是顶尖大厂呢还搞比赛抢hc,只能说应试者的痛苦考察方是无法理解的,他们只会想一出是一出
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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