如何设计实现一个LRU Cache?

1. 什么是LRU Cache?

在LeetCode上看到一个LRU Cache实现的题目,题目描述是这样的:

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

简单的说,就是保证基本的get和set的功能的同时,还要保证最近访问(get或put)的节点保持在限定容量的Cache中,如果超过容量则应该把LRU(近期最少使用)的节点删除掉。

那么我们思考一个问题:如何设计实现一个LRU Cache?
那么,我们可能需要使用类似这样的数据结构去实现这个LRU Cache:
这里写图片描述
当我们在get or set一个节点时都会把操作的这个节点移动到tail节点处,代表这个是最新操作的节点,head节点永远指向最老的节点,当超过设定的容量时,我们就删除head节点指向的最老节点。

其实上图就像是个LinkedHashMap,这样做的好处是,get和set在不冲突的情况下可以保证O(1)的复杂度,同时,也可以通过双向链表来保证LRU的删除和更新操作也能保证O(1)的复杂度。

当然上图可以简化一下head节点和tail节点变成一个head节点,形成一个环,这样head的next指向最旧的节点,prev指向最新的节点。

2.实现思路

在学习了HashMap和LinkedHashMap后,是不是觉得这俩数据结构简直太适合做LRU Cache了!那么动手实现一下:
基于HashMap和双向链表的实现

public class LRUCache<K , V> {

    class Node<K,V> {
        Node pre;
        Node next;
        private final K key;
        V val;

        Node(K k, V v) {
            key = k;
            val = v;
        }
    }

    Map<K, Node> map = new HashMap<K, Node>();

    // The head (eldest) of the doubly linked list.
    Node head;
    // The tail (youngest) of the doubly linked list.
    Node tail;

    int cap;

    public LRUCache(int capacity) {
        cap = capacity;
        head = new Node(null, null);
        tail = new Node(null, null);
        head.next = tail;
        tail.pre = head;
    }

    public V get(K key) {
        Node n = map.get(key);
        if(n!=null) {
            removeNode(n);
            appendTail(n);
            return (V) n.val;
        }
        return null;
    }

    public void set(K key, V value) {
        Node n = map.get(key);
        // existed
        if(n!=null) {
            n.val = value;
            map.put(key, n);
            removeNode(n);
            appendTail(n);
            return;
        }

        if(map.size() == cap) {
           removeLast();
        }
        n = new Node(key, value);
        // youngest node append tail
        appendTail(n);
        map.put(key, n);
    }

    //移除最近最少使用的节点,注意此节点就是head.next指向的节点
    public void removeLast() {
        Node tmp = head.next;
        removeNode(tmp);
        map.remove(tmp.key);
    }

    //移除某个节点,并将此节点的前后节点连接起来
    private void removeNode(Node n){
        n.pre.next = n.next;
        n.next.pre = n.pre;
    }

    //将节点加入到队列的尾部,尾部代表最近使用的节点
    private void appendTail(Node n) {
        n.next = tail;
        n.pre = tail.pre;
        tail.pre.next = n;
        tail.pre = n;
    }
}

基于LinkedHashMap的实现

public class LRUCache<K , V> {

    private int capacity;
    private Map<K, V> cache;

    public LRUCache(final int capacity) {
        this.capacity = capacity;
        this.cache = new java.util.LinkedHashMap<K, V> (capacity, 0.75f, true) {
            // 定义put后的移除规则,大于容量就删除eldest
            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
                return size() > capacity;
            }
        };
    }

    public V get(K key) {
        if (cache.containsKey(key)) {
            return cache.get(key);
        } else
            return null;
    }

    public void set(K key, V value) {
        cache.put(key, value);
    }
}


更多精彩Android技术可以关注我们的微信公众号,扫一扫下方的二维码或搜索关注公众号:


Android老鸟
这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值