LRU缓存算法的实现

7 篇文章 0 订阅

题目描述
这个问题在leetcode146题中有具体介绍,具体为:
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。
进阶:
你是否可以在 O(1) 时间复杂度内完成这两种操作?

思路
要在O(1)时间复杂度内完成get和put操作,key与value必须存入到map中,如何确定最近使用最少这一性质呢,这里涉及到最近使用时间的排序问题,每次改动必然导致相关数据的删除,进而优先级顺序发生改变,因此可以考虑使用链表结构,head存储最近一次访问的值,tail存储最后一次访问的value。每次put或者get操作将当前值对应的节点移动到链表的表头。
具体Java语言实现为:采用HashMap存储key与value,双向链表结构表示数据value的访问顺序,为什么必须要用双向链表呢,因为我们需要删除操作,删除一个节点不仅要得到该节点本身的指针,也需要操作其前驱节点的指针,而双向链表才能支持直接查找前驱,保证操作的时间复杂度 O(1)。
head节点便于快速移动到头结点。
由于size的限制,这里tail节点必不可少。
//参考左程云算法视频,对于当前访问的数据放在链表头部,当数据容量超过设定容量时,从头部删除。

leetcode146题答案

package practise;

import java.util.HashMap;
import java.util.Map;

public class LRU {
    private int SIZE = 100;  //最大容量

    private Node first;

    private Node tail;

    private Map<Integer, Node> map;


    class Node {
        private int k;
        private int v;
        private Node next;
        private Node pre;

        public Node(int k, int v) {
            this.k = k;
            this.v = v;
        }
    }

    public LRU(int capacity) {
        this.SIZE = capacity;
        this.map = new HashMap<>();
    }

    public Integer get(Integer key) {
        Node v = map.get(key);
        if (v == null) {
            return -1;
        }
        moveToHead(v);
        return v.v;
    }

    private void moveToHead(Node v) {
        if (v == first) {  // 本身是头结点
            return;
        } else if(v.next == null){    // 本身是尾节点,更新尾节点
            v.pre.next = null;
            this.tail = v.pre;
        } else {
            v.pre.next = v.next;
            v.next.pre = v.pre;   // 前后节点连在一起
        }

        v.next = first;          // 移到头结点
        first.pre = v;
        first = v;               // 重新定义头结点
    }

    public void put(Integer k, Integer v) {
        Node value = map.get(k);
        if (value != null) {
            if (value.v != v) {
                value.v = v;
            }
            moveToHead(value);
        } else {
            Node newValue = new Node(k, v);
            addToHead(newValue);
            map.put(k, newValue);
        }
    }

    private void addToHead(Node newValue) {
        if(first == null) {
            first = newValue;
            tail = newValue;
            return;
        }
        if (SIZE == 1) {        //只能放一个元素,直接替换
            map.remove(tail.k);
            tail = newValue;
            first = newValue;
            return;
        }
        if (map.size() >= SIZE) {
            removeTail();
        }
        newValue.next = first;
        first.pre = newValue;
        first = newValue;
    }

    private void removeTail() {
        map.remove(tail.k);
        Node pre = tail.pre;
        pre.next = null;
        tail = pre;
    }

}

对于key是自定义结构,我们扩充算法到一般情形

package practise;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.concurrent.locks.ReentrantLock;

public class Cache<K, V> {
    public static class Node<V> {
        public V value;
        public Node<V> last;
        public Node<V> next;

        public Node(V value) {
            this.value = value;
        }
    }

    public static class NodeDoubleLinkedList<V> {
        private Node<V> head; //队头
        private Node<V> tail; //队尾

        public NodeDoubleLinkedList() {
            this.head = null;
            this.tail = null;
        }

        public void addNode(Node<V> newNode) {
            if (newNode == null) {
                return;
            }
            if (this.head == null) {
                this.head = newNode;
                this.tail = newNode;
            } else {
                this.tail.next = newNode;
                newNode.last = this.tail;
                this.tail = newNode;
            }
        }

        public void moveNodeToTail(Node<V> node) {
            if (this.tail == node) {
                return;
            }
            if (this.head == node) {
                this.head = node.next;
                this.head.last = null;
            } else {
                node.last.next = node.next;
                node.next.last = node.last;
            }
            node.last = this.tail;
            node.next = null;
            this.tail.next = node;
            this.tail = node;
        }

        public Node<V> removeHead() {
            if (this.head == null) {
                return null;
            }
            Node<V> res = this.head;
            if (this.head == this.tail) {
                this.head = null;
                this.tail = null;
            } else {
                this.head = res.next;
                res.next = null;
                this.head.last = null;
            }
            return res;
        }

    }

    public static class MyCache<K, V> {
        private HashMap<K, Node<V>> keyNodeMap;
        private HashMap<Node<V>, K> nodeKeyMap;
        private NodeDoubleLinkedList<V> nodeList;
        private int capacity;

        public MyCache(int capacity) {
            if (capacity < 1) {
                throw new RuntimeException("should be more than 0.");
            }
            this.keyNodeMap = new HashMap<K, Node<V>>();
            this.nodeKeyMap = new HashMap<Node<V>, K>();
            this.nodeList = new NodeDoubleLinkedList<V>();
            this.capacity = capacity;
        }

        public V get(K key) {
            if (this.keyNodeMap.containsKey(key)) {
                Node<V> res = this.keyNodeMap.get(key);
                this.nodeList.moveNodeToTail(res);
                return res.value;
            }
            return null;
        }

        public void set(K key, V value) {
            if (this.keyNodeMap.containsKey(key)) {
                Node<V> node = this.keyNodeMap.get(key);
                node.value = value;
                this.nodeList.moveNodeToTail(node);
            } else {
                Node<V> newNode = new Node<V>(value);
                this.keyNodeMap.put(key, newNode);
                this.nodeKeyMap.put(newNode, key);
                this.nodeList.addNode(newNode);
                if (this.keyNodeMap.size() == this.capacity + 1) {
                    this.removeMostUnusedCache();
                }
            }
        }

        private void removeMostUnusedCache() {
            Node<V> removeNode = this.nodeList.removeHead();
            K removeKey = this.nodeKeyMap.get(removeNode);
            this.nodeKeyMap.remove(removeNode);
            this.keyNodeMap.remove(removeKey);
        }

    }

    public static void main(String[] args) {
        MyCache<String, Integer> testCache = new MyCache<String, Integer>(3);
        testCache.set("A", 1);
        testCache.set("B", 2);
        testCache.set("C", 3);
        System.out.println(testCache.get("B"));  // 返回2
        System.out.println(testCache.get("A"));  // 返回1
        testCache.set("D", 4);
        System.out.println(testCache.get("D")); // 返回4
        System.out.println(testCache.get("C"));// 返回null
        System.out.println(testCache.get("A"));// 返回1
    }



}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现LRU缓存淘汰算法的一种常用方法是使用哈希表和双向链表结合实现。具体实现步骤如下: 1. 使用一个哈希表来存储缓存中的键值对,其中键为缓存的键,值为该键对应的节点在双向链表中的指针。 2. 使用一个双向链表来存储缓存中的键值对,每个节点包含该节点对应的键、值以及前驱和后继指针。 3. 当有新的键值对被访问时,首先在哈希表中查找该键是否存在,如果存在,则将该键所对应的节点移到链表头部,表示最近被访问过;如果不存在,则在哈希表和链表中分别添加该键值对以及节点,并将该节点插入到链表头部。 4. 当缓存空间不足时,淘汰链表尾部的节点,并在哈希表中删除对应的键值对。 下面是一个Python实现LRU缓存淘汰算法的代码示例: ```python class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = {} self.head = Node(0, 0) self.tail = Node(0, 0) self.head.next = self.tail self.tail.prev = self.head def get(self, key: int) -> int: if key in self.cache: node = self.cache[key] self._remove(node) self._add(node) return node.val else: return -1 def put(self, key: int, value: int) -> None: if key in self.cache: self._remove(self.cache[key]) node = Node(key, value) self.cache[key] = node self._add(node) if len(self.cache) > self.capacity: node = self.head.next self._remove(node) del self.cache[node.key] def _add(self, node): p = self.tail.prev p.next = node node.prev = p node.next = self.tail self.tail.prev = node def _remove(self, node): p = node.prev n = node.next p.next = n n.prev = p class Node: def __init__(self, key, val): self.key = key self.val = val self.prev = None self.next = None ``` 在这个实现中,我们使用一个双向链表来维护缓存中节点的顺序,其中head和tail分别是链表的头节点和尾节点。同时,我们使用一个哈希表来查询节点是否存在以及快速删除节点。当有新的节点被访问时,我们将其移到链表头部,并且当缓存空间不足时,我们淘汰链表尾部的节点。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值