[双向链表&哈希] LeetCode 146. LRU 缓存

8 篇文章 1 订阅

LeetCode 146. LRU 缓存

https://leetcode.cn/problems/lru-cache/

Solution(Java)

class LRUCache {
    private int capacity;
    private int curSize;    
    private Map<Integer, Node> cache;
    private Node head;
    private Node tail;

    // 双向链表节点
    static class Node {
        Node pre;
        Node next;
        int key;
        int val;
        public Node() {}
        
        public Node(int key, int val) {
        	this.key = key;
            this.val = val;
        }

        public Node(int key, int val, Node pre, Node next) {
            this.key = key;
            this.val = val;
            this.pre = pre;
            this.next = next;
        }
    }
    /**
     * 初始化双向链表
     */
    private void initLinkedList() {
        this.head = new Node();
        this.tail = new Node();
        this.head.next = tail;
        this.tail.pre = head;
    }

    /**
     * 删除节点
     */
    private void removeNode(Node node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }
    
    /**
     *  移动到头结点
     */
    private void moveToHead(Node node) {
        node.pre = head;
        node.next = head.next;
        head.next.pre = node;
        head.next = node;
    }

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.curSize = 0;
        this.cache = new HashMap<>();

        initLinkedList();
    }
    
    /**
     * 当节点不存在 return -1; 若存在,将节点移动到头结点
     */
    public int get(int key) {
        Node node = this.cache.get(key);
        if (node != null) {
            removeNode(node);
            moveToHead(node);
            return node.val;
        }
        return -1;
    }
    
    /**
     * 将节点加入到头节点,若容器满,删除尾节点
     */
    public void put(int key, int value) {
        Node node = this.cache.get(key);
        if (node != null) {
            node.val = value;
            removeNode(node);
            moveToHead(node);
        } else {
            Node newNode = new Node(key, value);
            moveToHead(newNode);
            this.cache.put(key, newNode);
            this.curSize++;
            
            if (this.curSize > capacity) {
                this.cache.remove(this.tail.pre.key);
                removeNode(this.tail.pre);
                this.curSize--;
            }
        }
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哇咔咔负负得正

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值