手写LRU

描述:

LRU,在缓存中删除总是删除最近最少使用的key

思路分析:

1、缓存实现:查询、更新,一定是使用HashMap
2、通过链表来判断最近最少使用的是哪一个,即:最近有使用的放链表头、最近最少使用的放链表尾
3、因为需要删除链表中某个过期的节点,所以选择使用双向链表
4、HashMap中key就存查询搜索的key;value存放双向链表的节点

代码实现:
package com.qu;

import java.util.HashMap;

/**
 * @title: LRUCache
 * @description: 手写实现lru缓存、每次淘汰最近最少使用的
 * @author:quLiangquan
 * @date 2019/8/16 14:19
 **/
class LRUCache {
    private static class DLinkedNode {
        int key;
        int value;
        DLinkedNode pre;
        DLinkedNode next;
    }

    private HashMap<Integer, DLinkedNode> cache = new HashMap<>();
    private int capacity;
    private int count;
    private DLinkedNode head, tail;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.count = 0;
        this.head = new DLinkedNode();
        this.tail = new DLinkedNode();

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

	//get过后,需要把get的节点从链表中更新至链表头
    private void moveToHead(DLinkedNode node) {
        removeNode(node);
        addNode(node);
    }

    //把node从链表中移除
    private void removeNode(DLinkedNode node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }

    //把node加到链表头上去
    private void addNode(DLinkedNode node) {
        node.pre = head;
        node.next = head.next;
        head.next = node;
        node.next.pre = node;
    }

    //弹出最尾巴的节点
    private void popTail() {
        DLinkedNode res = tail.pre;
        removeNode(res);
        cache.remove(res.key);  //注意一定要把map中对应的key删掉
    }

    public int get(int key) {
        DLinkedNode node = cache.get(key);
        if (node == null) {
            return -1;
        }
        //获取之后,标记为最近使用的、node移动至链表头
        moveToHead(node);
        return node.value;
    }

    public void put(int key, int value) {
        DLinkedNode node = cache.get(key);
        if (node == null) {
            DLinkedNode newNode = new DLinkedNode();
            newNode.key = key;
            newNode.value = value;
            cache.put(key, newNode);
            addNode(newNode);
            ++count;
            if (count > capacity) {
                //超出容量了、把最后一个node弹出、并删除该noide、然后容量减一
                popTail();
                count--;
            }
        } else {
            node.value = value;
            moveToHead(node);
        }
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值