leetcode 146. LRU Cache 需要深入学习Java的Map的内部实现

本文介绍了一种使用Java实现的LRU缓存数据结构。该缓存支持get和put操作,并能在达到容量限制时移除最久未使用的项。通过继承LinkedHashMap并调整其行为来实现高效的数据管理和访问。

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

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.

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

我也是网上参考的教程。

强烈建议学习深入Java集合学习系列:HashMap的实现原理深入Java集合学习系列:LinkedHashMap的实现原理

代码如下:

import java.util.HashMap;
import java.util.LinkedHashMap;
/*
 * http://blog.youkuaiyun.com/HE19930303/article/details/51315263
 * 
 * http://zhangshixi.iteye.com/blog/673789 
 * 
 * http://zhangshixi.iteye.com/blog/672697
 * 
 * 这个题值得学习Java中的HashMap和LinkedHashMap
 * */
public class LRUCache extends LinkedHashMap<Integer,Integer>
{

    private int maxcapacity;
    public LRUCache(int capacity) 
    {
        super(capacity,0.75f,true);
        this.maxcapacity=capacity;
    }

    public int get(int key) 
    {
        Integer vaule=super.get(key);
        if(vaule==null)return -1;
        else return vaule;
    }

    public void set(int key, int value) 
    {
        super.put(key,value);
    }
    protected boolean removeEldestEntry(Map.Entry<Integer,Integer> eldest)
    {
        return size()>maxcapacity;
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */
### LeetCode 146 LRU Cache 的 C++ 实现 LRU(Least Recently Used)是一种常见的缓存淘汰策略,用于管理固定大小的内存空间。当缓存满时,会移除最近最少使用的数据项以腾出空间。 以下是基于双向链表和哈希表实现的 C++ 解决方案: #### 双向链表节点定义 为了高效地维护访问顺序并快速更新节点位置,可以使用自定义的 `ListNode` 类来表示双向链表中的节点。 ```cpp struct ListNode { int key; int value; ListNode* prev; ListNode* next; ListNode(int k, int v) : key(k), value(v), prev(nullptr), next(nullptr) {} }; ``` #### 缓存类设计 通过组合哈希表和双向链表,可以在 O(1) 时间复杂度下完成插入、删除以及查找操作。 ```cpp class LRUCache { private: unordered_map<int, ListNode*> map; // 哈希表存储键到节点指针的映射关系 ListNode* head; // 虚拟头结点 ListNode* tail; // 虚拟尾结点 int capacity; // 容量上限 public: LRUCache(int cap) : capacity(cap) { head = new ListNode(-1, -1); // 初始化虚拟头部 tail = new ListNode(-1, -1); // 初始化虚拟尾部 head->next = tail; // 连接首尾 tail->prev = head; } ~LRUCache() { ListNode* cur = head; while (cur != nullptr) { ListNode* temp = cur; cur = cur->next; delete temp; } } void removeNode(ListNode* node) { node->prev->next = node->next; node->next->prev = node->prev; } void addToHead(ListNode* node) { node->next = head->next; node->prev = head; head->next->prev = node; head->next = node; } int get(int key) { if (!map.count(key)) return -1; // 如果不存在该key,则返回-1 ListNode* node = map[key]; removeNode(node); addToHead(node); return node->value; } void put(int key, int value) { if (map.count(key)) { // 若已存在则更新其值并将它移到最前面 ListNode* node = map[key]; node->value = value; removeNode(node); addToHead(node); return; } if (map.size() >= capacity) { // 当容量达到上限时,移除最后未被使用的节点 ListNode* lastUsed = tail->prev; removeNode(lastUsed); map.erase(lastUsed->key); delete lastUsed; } ListNode* newNode = new ListNode(key, value); // 创建新节点并加入hashMap与链表前端 map[key] = newNode; addToHead(newNode); } }; ``` 上述代码实现了基本功能[^3],其中包含了以下几个核心部分: - **removeNode**: 将指定节点从当前列表中移除。 - **addToHead**: 把某个节点移动至链表开头的位置。 - **get 方法**: 获取对应 key 的值,并将其标记为最新访问过的项目。 - **put 方法**: 插入新的键值对或者覆盖已有条目;如果超出设定的最大数量限制,则清除掉最早之前加载的数据记录。 此版本的时间效率较高,在每次调用 `get()` 或者 `set()` 函数时都能保持常数级时间性能表现[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值