146. LRU Cache (M)

本文详细介绍了如何设计和实现一个最少最近使用(LRU)缓存机制,包括使用双向链表和HashMap的数据结构来实现get和put操作的时间复杂度为O(1),并提供了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LRU Cache (M)

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(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.

The cache is initialized with a positive capacity.

Follow up:
Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4

题意

实现一个LRU缓存机制:查询时,如果不存在目标key,则返回-1,否则返回key对应的value;插入时,如果缓存已满,则将访问时间最远的(key, value)对删去,存入新的(key, value)对。

思路

主要思想是维护一个类数组结构,越近访问的数据越靠近头部,越远访问的数据越靠近尾部。每次查询到旧值或访问新值时,将该值从原位置取出并插入到头部;需要删除数据时,只要删去尾部的数据。

具体实现使用双向链表+HashMap:双向链表使得删除和移动结点的复杂度为 O ( 1 ) O(1) O(1);HashMap用于创建索引,将key值映射到对应的结点,使结点查询复杂度也为 O ( 1 ) O(1) O(1)


代码实现

class LRUCache {
    // 双向链表结点
    class Node {
        int key, val;
        Node prev, next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    private Node head, tail;
    private int capacity;
    private Map<Integer, Node> hash;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        hash = new HashMap<>();
        // dummy结点可以大大简化步骤
        head = new Node(-1, -1);
        tail = new Node(-1, -1);
        head.next = tail;
    }

    public int get(int key) {
        if (!hash.containsKey(key)) {
            return -1;
        }

        // 查询到存在,则将原结点拎出插入到头结点之后
        Node target = hash.get(key);
        removeFromPos(target);
        moveToFirst(target);
        return target.val;
    }

    public void put(int key, int value) {
        if (!hash.containsKey(key)) {
            // 需要插入新值,则新建结点并将其移动到头结点后
            Node temp = new Node(key, value);
            hash.put(key, temp);
            moveToFirst(temp);
        } else {
            // 更新旧值,并将原结点取出插入到头结点之后
            Node target = hash.get(key);
            target.val = value;
            removeFromPos(target);
            moveToFirst(target);
        }
        
        // 超出容量,则删去尾结点之前的结点
        if (hash.size() == capacity + 1) {
            hash.remove(tail.prev.key);
            removeFromPos(tail.prev);
        }
    }

    // 将目标结点移动到头结点之后
    private void moveToFirst(Node target) {
        target.next = head.next;
        head.next.prev = target;
        target.prev = head;
        head.next = target;
    }

    // 将目标结点从链中取出
    private void removeFromPos(Node target) {
        target.prev.next = target.next;
        target.next.prev = target.prev;
        target.next = null;
        target.prev = null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值