【Java】【LeetCode】146. LRU Cache

LeetCode 精选 TOP 面试题(Java 实现)—— LRU缓存机制 文章目录一、题目描述1.1 题目1.2 知识点1.3 题目链接二、解题思路2.1 自研思路三、实现代码3.1 自研实现 一、题目描述 1.1 题目 LRU缓存机制 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的... 阅读详情

题目:

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

题解:

这道题是一个数据结构设计题,在leetcode里面就这么一道,还是挺经典的一道题,可以好好看看。

这道题要求设计实现LRU cache的数据结构,实现set和get功能。学习过操作系统的都应该知道,cache作为缓存可以帮助快速存取数据,但是确定是容量较小。这道题要求实现的cache类型是LRU,LRU的基本思想就是“最近用到的数据被重用的概率比较早用到的大的多”,是一种更加高效的cache类型。

解决这道题的方法是:双向链表+HashMap

“为了能够快速删除最久没有访问的数据项和插入最新的数据项,我们将双向链表连接Cache中的数据项,并且保证链表维持数据项从最近访问到最旧访问的顺序。 每次数据项被查询到时,都将此数据项移动到链表头部(O(1)的时间复杂度)。这样,在进行过多次查找操作后,最近被使用过的内容就向链表的头移动,而没 有被使用的内容就向链表的后面移动。当需要替换时,链表最后的位置就是最近最少被使用的数据项,我们只需要将最新的数据项放在链表头部,当Cache满 时,淘汰链表最后的位置就是了。 ”

 “注: 对于双向链表的使用,基于两个考虑。

            首先是Cache中块的命中可能是随机的,和Load进来的顺序无关。

         其次,双向链表插入、删除很快,可以灵活的调整相互间的次序,时间复杂度为O(1)。”

解决了LRU的特性,现在考虑下算法的时间复杂度。为了能减少整个数据结构的时间复杂度,就要减少查找的时间复杂度,所以这里利用HashMap来做,这样时间复杂度就是O(1)。

 所以对于本题来说:

get(key): 如果cache中不存在要get的值,返回-1;如果cache中存在要找的值,返回其值并将其在原链表中删除,然后将其作为头结点。

set(key,value):当要set的key值已经存在,就更新其value, 将其在原链表中删除,然后将其作为头结点;当药set的key值不存在,就新建一个node,如果当前len<capacity,就将其加入hashmap中,并将其作为头结点,更新len长度,否则,删除链表最后一个node,再将其放入hashmap并作为头结点,但len不更新。

 

原则就是:对链表有访问,就要更新链表顺序。 

代码如下:

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

public class LRUCache
{

    public static void main(String[] args)
    {
        /**
         * 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);
        System.out.println(cache.get(1)); // returns 1
        cache.put(3, 3); // evicts key 2
        System.out.println(cache.get(2)); // returns -1 (not found)
        cache.put(4, 4); // evicts key 1
        System.out.println(cache.get(1)); // returns -1 (not found)
        System.out.println(cache.get(3)); // returns 3
        System.out.println(cache.get(4)); // returns 4
    }

    private int capacity;

    private LinkedList<Integer> list = new LinkedList<Integer>();

    private Map<Integer, Integer> map = new HashMap<Integer, Integer>();

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

    public int get(int key)
    {
        if (map.containsKey(key))
        {
            list.remove(new Integer(key));
            list.offerFirst(key);
            return map.get(key);
        }
        else
        {
            return -1;
        }
    }

    public void put(int key, int value)
    {
        if (map.containsKey(key))
        {
            list.remove(new Integer(key));
        }
        else
        {
            if (capacity <= map.size())
            {
                Integer lastKey = list.pollLast();
                map.remove(lastKey);
            }
        }
        list.offerFirst(key);
        map.put(key, value);
    }

    /**
     * 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);
     */
}

 

别再死记硬背Modbus报文了!用Python+Modbus Poll手把手教你调试工业设备 本文详细介绍了如何利用Python和Modbus Poll工具高效调试工业设备通信。通过实战案例和代码示例,帮助读者快速掌握Modbus通信协议的核心配置、数据监控技巧及Python自动化脚本编写,解决工业设备调试中的常见问题,提升工作效率。 阅读详情

相关推荐

Supreme小程序自动化抢购终端——源码架构与执行流程全解析

本系统是一套基于开发的桌面端小程序自动化抢购终端。把只有开发者能跑的脚本,包装成普通用户也能操作的桌面工具。参数自动捕获 → 商品多关键词检索 → sku/尺码/库存映射 → 多商品任务队列 → 定时/立即抢购 → 订单创建 → 支付参数拉取 → 本地服务生成支付链接 → 手机微信扫码付款这套 Supreme 抢购终端,表面上看是一个"下单工具"。但从工程角度审视,它已经具备了一个小型桌面自动化系统GUI 层:CustomTkinter 现代化界面,线程安全业务层:多商品队列、定时调度、任务编排。

猫敷雪 175

LruCache报错IllegalStateException

描述 定义LruCache: LruCache cache = new LruCache<String, List<?>>(maxSize){ @Override protected int sizeOf(String key, List<?> value){ return EmptyUtil.isEmpty(value) ? 1 : value.siz...

BIGGGFISH的博客 1606

前台后台网页模板

前台后台网页模板javaweb仅限于自己使用

力扣(LeetCode146.LRU缓存(java

请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。

Cnc2014的博客 485

leetcode146. LRU缓存机制 — Java实现

LFUCache Java实现 实现1: import java.util.LinkedHashMap; import java.util.HashMap; import java.lang.IllegalArgumentException; import java.util.Map; public class LRUCache<K, V> extends Link...

永生只是一场幻梦 4534

Leetcode LRU缓存的java实现及解析

Leetcode LRU缓存的java实现及解析 LRU是least recent used的缩写,顾名思义就是最近没有用过的元素,LRU缓存的知识还是大三的时候学系统的时候学到的,其实就是一种类似提高缓存使用率的方式。大家都直到缓存其实是很小的,但是速度却非常的快,怎么样决定缓存里面存储什么样的元素很直接地影响系统的效率,当我们需要调用一个文件的时候系统会先去缓存里面找,如果找到了就返回,如果没找到才会去其他的地方找。 LRU就是一种决定缓存内容的方式,也就是如果我们要放入缓存的内容大于缓存的容量,我们就

Dh0le的博客 590

LeetCode146):LRU缓存机制 LRU CacheJava

2019.7.27 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新) 数据结构的基础知识题,做完之后能够更加深刻地理解LRU缓存的机制。 配合使用双向链表和哈希表,双向链表的尾部为最近最少使用结点,每次put和get时将对应结点更新到双向链表头部。 传送门:LRU缓存机制 Design and implement a data structure for Least Re...

NJU_ChopinXBP的博客 574

LeetCode 146.LRU CacheJava

题目描述 https://leetcode-cn.com/problems/lru-cache/ AC代码 class LRUCache { private HashMap<Integer,Integer> map=new HashMap<>(); private LinkedList<Integer> list=new LinkedList&l...

NayelyA的博客 234

【算法】Java实现LRU Cache 缓存 LeetCode146

LRU (Least Recently Used) Cache 最近最少使用的缓存。 实现思想:借用双链表和map实现,双链表保存实际的值,map用来保存key和链表节点的映射关系。 class LRUCache { int capacity; // 保护节点 Node head; Node tail; Map<Integer, Node> cache = new HashMap<>(); public LRUCache(in

未闻花名丶的博客 1102

LeetCode-146. LRU Cache [C++][Java]

Design a data structure that follows the constraints of aLeast Recently Used (LRU) cache.

贫道绝缘子的博客 1287

[LeetCode] 146. LRU Cache java

/**146. LRU Cache * @date: 2016年10月27日 * @description: http://blog.csdn.net/sbitswc/article/details/35899935 */ private HashMap<Integer, DoubleLinkedListNode> map = new HashMap<Integ

橙煦媛的博客 846

Java for LeetCode 146 LRU Cache 【HARD】

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 t...

weixin_30764771的博客 128

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

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 k

JackZhangNJU的专栏 1431

LeetCode Top 100 Liked Questions 146. LRU Cache (Java版; Medium)

welcome to my blog LeetCode Top 100 Liked Questions 146. LRU Cache (Java版; Medium) 题目描述 Design and implement a data structure for Least Recently Used (LRU,最近最少使用) cache. It should support the followin...

littlehaes的博客 156

leetcode 146. LRU Cache ----- java

esign and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:getandset. get(key)- Get the value (will always be positive) of the key if the...

weixin_30856725的博客 113

leetcode146.LRU缓存机制 (哈希表+双向链表,java实现)

146. LRU缓存机制 难度中等 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。 写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空

Viper的程序员修炼手册 749

leetcode146.手撸 LRU 算法(java)

LRU 缓存淘汰算法就是一种常用策略。LRU 的全称是 Least Recently Used,也就是说我们认为最近使用过的数据应该是是「有用的」,很久都没用过的数据应该是无用的,内存满了就优先删那些很久没用过的数据。

SP_1024的博客 480

面试大厂最常考算法之一LRU缓存算法

题目 146. LRU 缓存机制 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。 实现 LRUCache 类: LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存 int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。 void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限

qq_23923713的博客 505

Leetcode 146. LRU 缓存。 手撕lru? 面试官让手写lrujava版本lru

当访问一个节点时,如果节点存在,我们将其从原来的位置删除,并重新插入到链表头部。这样就能保证链表尾部存储的就是最近最久未使用的节点,当节点数量大于缓存最大空间时就淘汰链表尾部的节点。当插入一个节点时,如果节点存在,我们将其从原来的位置删除,并重新插入到链表头部。如果不存在,我们首先检查缓存是否已满,如果已满,则删除链表尾部的节点,将新的节点插入链表头部。// 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}// 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}// 缓存是 {1=1}

求是 1540

Leetcode-146 LRU缓存(java中封装好的)

力扣题目解题思路java代码。

LIUCHANGSHUO的博客 624

LeetCode Hot100题目解析:LRU缓存机制(哈希表+双向链表 Java详解)

运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作:获取数据 get 和写入数据 put。

weixin_46532327的博客 593
上一篇: 【Java】【LeetCode】143. Reorder List
下一篇: 【Java】【LeetCode】71. Simplify Path
狗辣子
博客等级 码龄12年 2粉丝 141原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值