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.

思路1:用哈希

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeMap;

public class LRUCache {
	private static int idx = 0;
    class Node {
		Integer order; 
        Integer v; // v is value
        public Node(int key, int value) {
        	order = key;
        	v = value;
		}
    }
    private TreeMap<Integer, Integer> cacheIndex = new TreeMap<Integer, Integer>();// id -> key
    private HashMap<Integer, Node> cache = new HashMap<Integer, Node>(); // key -> Node
    private int capacity;
    
    public LRUCache(int capacity) {
        this.capacity = capacity;
    }
    
    public int get(int key) {
        if(cache.containsKey(key)) {
            return update(key).v;
        }
        return -1;
    }
    
    public void set(int key, int value) {
        if(cache.size() >= capacity && !cache.containsKey(key)) {
            Entry<Integer, Integer> first = cacheIndex.firstEntry();
            cacheIndex.remove(first.getKey());
            cache.remove(first.getValue());
        }
        if(cache.containsKey(key)) {
            Node node = update(key);
            node.v = value;
        } else {
            addNode(key, value);
        }
    }
    
    // create a new node and add to cache
    private void addNode(int key, int value) {
        ++LRUCache.idx;
        Node node = new Node(LRUCache.idx, value);
        cache.put(key, node);
        cacheIndex.put(LRUCache.idx, key);
    }
    
    // return the node by key
    private Node update(int key) {
        ++LRUCache.idx;
        Node node = cache.get(key);
        cacheIndex.remove(node.order);
        node.order = LRUCache.idx;
        cacheIndex.put(LRUCache.idx, key);
        return node;
    }
}

思路2:

用链表,借用这里

public class LRUCache {

	class Node {
		int key;
		int value;
		Node pre;
		Node next;

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

	private int capacity;
	private HashMap<Integer, Node> map = new HashMap<Integer, Node>();
	private Node head = null;
	private Node end = null;

	public LRUCache(int capacity) {
		this.capacity = capacity;
	}

	public int get(int key) {
		if (map.containsKey(key)) {
			Node n = map.get(key);
			remove(n);
			setHead(n);
			return n.value;
		}

		return -1;
	}

	private void remove(Node n) {
		if (n.pre != null) {
			n.pre.next = n.next;
		} else {
			head = n.next;
		}

		if (n.next != null) {
			n.next.pre = n.pre;
		} else {
			end = n.pre;
		}

	}

	private void setHead(Node n) {
		n.next = head;
		n.pre = null;

		if (head != null)
			head.pre = n;

		head = n;

		if (end == null)
			end = head;
	}

	public void set(int key, int value) {
		if (map.containsKey(key)) {
			Node old = map.get(key);
			old.value = value;
			remove(old);
			setHead(old);
		} else {
			Node created = new Node(key, value);
			if (map.size() >= capacity) {
				map.remove(end.key);
				remove(end);
				setHead(created);

			} else {
				setHead(created);
			}

			map.put(key, created);
		}
	}
}


<think>好的,用户想了解LRU缓存的工作原理和实现方法。首先,我需要回忆LRU的基本概念,确定LRU是Least Recently Used的缩写,即最近最少使用算法,常用于缓存淘汰策略。接下来,工作原理部分需要解释当缓存容量满时,如何选择最久未被访问的数据进行淘汰。这里可能需要结合数据结构,比如哈希表和双向链表,来说明如何高效地实现访问顺序的维护。 然后是具体实现方法。常见的实现方式确实是用哈希表加双向链表。哈希表用于快速定位节点,双向链表则维护访问顺序。最近访问的节点移到链表头部,最久未使用的在尾部。当插入新数据时,如果缓存已满,就删除尾部节点。这部分需要详细说明每个操作的步骤,比如访问、插入、删除等,以及它们的时间复杂度。 可能还需要提到其他实现方式,比如使用OrderedDict的数据结构,这在Python中确实存在,可以简化实现。但如果是其他语言,可能需要自己构建双向链表和哈希表。这部分可以作为不同实现方法的补充说明。 接下来,用户可能关心LRU的应用场景,比如数据库缓存、页面置换算法等,但用户的问题主要集中在实现和工作原理,所以这部分可能不需要深入,但可以作为相关问题提出。 然后,根据用户提供的引用,我需要检查是否有相关引用可以支持回答。但查看用户提供的引用内容,引用1是关于流处理和响应式编程的库,引用2是机器学习在GPU集群调度的应用,引用3是Go语言编译工具,似乎和LRU缓存没有直接关联。因此,可能无法直接引用这些内容,需要忽略引用部分,或者寻找间接关联点,但可能不太相关。 在生成相关问题的时候,需要考虑用户可能进一步想了解的内容,比如LRU的变种、时间复杂度分析、实际应用中的挑战、与其他算法比较等。例如,如何保证O(1)时间复杂度,如何处理并发访问,LRU的缺点以及改进算法如LRU-K等。 最后,代码示例部分需要确保正确性。Python中使用OrderedDict是一个典型的实现方式,每次访问时移动键到最新位置,插入时检查容量并弹出最久未使用的项。需要确保代码示例简洁,并且注释清晰,方便用户理解。 总结整个思考过程,需要将LRU的工作原理和实现方法清晰地分点解释,结合数据结构和操作步骤,给出代码示例,并生成相关问题,引导用户深入理解。同时注意用户提到的系统级指令,如数学公式的正确格式,但LRU内容可能较少涉及数学公式,所以主要关注代码块和结构。</think>### LRU缓存实现原理 LRU(Least Recently Used)缓存淘汰策略基于"最近最少使用"原则,当缓存容量满时淘汰最久未被访问的数据。其核心数据结构组合为: 1. **哈希表**:实现$O(1)$时间复杂度的键值查询 2. **双向链表**:维护键的访问顺序,最近访问的节点靠近头部 ### 操作过程 1. **访问数据**: - 通过哈希表定位节点 - 将节点移动到链表头部(表示最近使用) - 时间复杂度:$O(1)$ 2. **插入数据**: ```python if 键已存在: 更新值并移动节点到链表头部 else: 创建新节点并添加到链表头部 if 缓存已满: 删除链表尾部节点 从哈希表删除对应键 ``` ### Python实现示例 ```python from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.cache = OrderedDict() self.capacity = capacity def get(self, key: int) -> int: if key not in self.cache: return -1 self.cache.move_to_end(key) return self.cache[key] def put(self, key: int, value: int) -> None: if key in self.cache: self.cache.move_to_end(key) self.cache[key] = value if len(self.cache) > self.capacity: self.cache.popitem(last=False) ``` ### 性能特征 - **时间复杂度**:所有操作保持$O(1)$ - **空间复杂度**:$O(n)$,n为缓存容量 - **适用场景**:符合局部性原理的访问模式,如数据库缓存、CDN缓存等[^1]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值