Leetcode 中等:146. LRU缓存机制

LeetCode146——LRU缓存机制 我的LeetCode代码仓:https://github.com/617076674/LeetCode 原题链接:https://leetcode-cn.com/problems/lru-cache/description/ 题目描述: 知识点:哈希表、双向链表、LRU缓存机制 思路一:用哈希表记录键值对,用双向链表处理LRU缓存机制 用示例来说明我们算法的流程,为了防止对null节... 阅读详情

题目:LRU缓存机制

  • 题号:146
  • 难度:中等
  • https://leetcode-cn.com/problems/lru-cache/

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

实现 LRUCache 类:

  • LRUCache(int capacity) 以 正整数 作为容量 capacity 初始化 LRU 缓存。
  • int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
  • void put(int key, int value)如果关键字 key 已经存在,则变更其数据值 value ;如果不存在,则向缓存中插入该组 key-value 。如果插入操作导致关键字数量超过 capacity ,则应该 逐出 最久未使用的关键字。

函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。

示例:

输入
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
输出
[null, null, null, 1, null, -1, null, -1, 3, 4]

解释
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1);    // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
lRUCache.get(2);    // 返回 -1 (未找到)
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
lRUCache.get(1);    // 返回 -1 (未找到)
lRUCache.get(3);    // 返回 3
lRUCache.get(4);    // 返回 4

提示:

  • 1 <= capacity <= 3000
  • 0 <= key <= 10000
  • 0<=value<=1050 <= value <= 10^50<=value<=105

最多调用 2∗1052 * 10^52∗105 次 get 和 put。


实现

计算机的缓存容量有限,如果缓存满了就要删除一些内容,给新内容腾位置。但问题是,删除哪些内容呢?我们肯定希望删掉哪些没什么用的缓存,而把有用的数据继续留在缓存里,方便之后继续使用。那么,什么样的数据,我们判定为「有用的」的数据呢?

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

第一种:利用单链表的方式:

public class LRUCache
{
    private readonly int _length;
    private readonly List<KeyValuePair<int, int>> _lst;

    public LRUCache(int capacity)
    {
        _length = capacity;
        _lst = new List<KeyValuePair<int, int>>();
    }

    private int GetIndex(int key)
    {
        for (int i=0,len=_lst.Count;i<len;i++)
        {
            if (_lst[i].Key == key)
            {
                return i;
            }
        }
        return -1;
    }

    public int Get(int key)
    {
        int index = GetIndex(key);
        if (index!=-1)
        {
            int val = _lst[index].Value;
            _lst.RemoveAt(index);
            _lst.Add(new KeyValuePair<int, int>(key, val));
            return val;
        }
        return -1;
    }

    public void Put(int key, int value)
    {
        int index = GetIndex(key);
        if (index!=-1)
        {
            _lst.RemoveAt(index);
        }
        else if (_lst.Count == _length)
        {
            _lst.RemoveAt(0);
        }
        _lst.Add(new KeyValuePair<int, int>(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);
 */

第二种:利用 字典 + 列表 的方式:

把字典当作一个存储容器,由于字典是无序的,即 dict 内部存放的顺序和 key 放入的顺序是没有关系的,所以需要一个 list 来辅助排序。

C# 语言

public class LRUCache
{
    private readonly List<int> _keys;
    private readonly Dictionary<int, int> _dict;

    public LRUCache(int capacity)
    {
        _keys = new List<int>(capacity);
        _dict = new Dictionary<int, int>(capacity);
    }

    public int Get(int key)
    {
        if (_dict.ContainsKey(key))
        {
            _keys.Remove(key);
            _keys.Add(key);
            return _dict[key];
        }
        return -1;
    }

    public void Put(int key, int value)
    {
        if (_dict.ContainsKey(key))
        {
            _dict.Remove(key);
            _keys.Remove(key);
        }
        else if (_keys.Count == _keys.Capacity)
        {
            _dict.Remove(_keys[0]);
            _keys.RemoveAt(0);
        }
        _keys.Add(key);
        _dict.Add(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);
 */

Python 语言

class LRUCache(object):
    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self._capacity = capacity
        self._dict = dict()
        self._keys = list()

    def get(self, key):
        """
        :type key: int
        :rtype: int
        """
        if key in self._dict:
            self._keys.remove(key)
            self._keys.append(key)
            return self._dict[key]
        return -1

    def put(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: None
        """
        if key in self._dict:
            self._dict.pop(key)
            self._keys.remove(key)
        elif len(self._keys) == self._capacity:
            self._dict.pop(self._keys[0])
            self._keys.remove(self._keys[0])
        self._keys.append(key)
        self._dict[key] = value


# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
【LeetCode 热题100】 146. LRU 缓存的算法思路及python代码 请你设计并实现一个满足缓存 约束的数据结构。实现LRUCachecapacitykeykeyvaluekey-valuecapacity函数get和put必须以O1的平均时间复杂度运行。 阅读详情

相关推荐

LeetCode146: LRU缓存机制(字节面试手撕题)

文章目录前言题干举个栗子具体学习实现LinkedList+HashMap双向链表+HashMap节点的定义:双向链表API具体执行过程后记 前言 之前在校学习计算机操作系统时候学习过,当时就明白了个什么意思,但是具体的实现老师并没有给我们要求,当时也就没有具体的深入学习,这段时间发现对于基础的部分还是蛮重要的。加上发现对于最近的面试来说这个还蛮重要的,所以这里拿出来自己进行记录一下,希望能帮助到在...

weixin_44015043的博客 808

146. LRU 缓存机制

146. LRU 缓存机制 题目 146. LRU 缓存机制 方法思路 双向链表+hashMap hashMap中保存key->node的映射关系 链表结点中需要保存key,value和前后指针 需要定义虚拟头节点和尾结点,方便插入和删除 将当使用一个结点时,需要将该节点加入头部,需要删除时,删除尾部的结点并且删除hashMap中的映射关系,就实现了LRU的机制 代码 // 双链表结点定义 struct Node { // 用来记录key,当删除双链表尾部时,可以通过key删除哈希表中

dengh571的博客 160

LeetCode 146 - LRU缓存机制

的结合使用,以及对缓存淘汰策略(Least Recently Used)的实现。该题目在工程实践中十分常见,解法及其变体对面试和实际生产开发都具有重要意义。通过大量练习,熟练掌握 LRU 的实现以及链表、哈希表的结合模式,能够快速解决缓存机制相关问题!以下详细讲解不同解法、模板代码以及相关变体问题,帮助快速掌握并解决类似系统设计类问题。是一道经典的数据结构设计问题,考察对。与 LRU 反向,淘汰最近使用的缓存。利用 Java 提供的。

互联网架构师笔记 1153

leetcode 146 LRU缓存机制

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

学习印记 Learning imprint 532

中兴OLT配置实战:从零开始,手把手教你完成一个HGU的完整业务开通(含DBA模板、限速与远程升级)

本文详细介绍了中兴OLT配置实战,从零开始手把手教你完成HGU的完整业务开通,包括DBA模板设计、限速与远程升级等关键步骤。通过实际案例和详细命令,帮助工程师快速掌握GPON网络配置技巧,提升运维效率。

weixin_30599769的博客 348

利用featureCounts实现高效转录本定量:从比对到下游分析

本文详细介绍了利用featureCounts工具进行RNA-seq转录本定量的完整流程。从软件安装、输入文件准备,到核心命令参数解析与批量样本处理,再到将生成的计数矩阵无缝衔接至DESeq2进行差异表达分析,提供了从比对到下游分析的一站式实战指南。文章重点阐述了featureCounts在效率与易用性上的优势,并分享了常见问题排查与性能优化技巧,帮助研究者高效完成转录本定量这一关键步骤。

weixin_29069131的博客 317

146. LRU缓存机制

一、什么是 LRU 算法 就是一种缓存淘汰策略。 计算机的缓存容量有限,如果缓存满了就要删除一些内容,给新内容腾位置。但问题是,删除哪些内容呢?我们肯定希望删掉哪些没什么用的缓存,而把有用的数据继续留在缓存里,方便之后继续使用。那么,什么样的数据,我们判定为「有用的」的数据呢? LRU 缓存淘汰算法就是一种常用策略。LRU 的全称是 Least Recently Used,也就是说...

INGNIGHT的专栏 320

CLIP-Count代码配置以及踩坑记录

CLIP-Count代码配置以及踩坑记录

学术菜鸡 1011

146-LRU缓存机制

class LRUCache { public: LRUCache(int capacity) { cap = capacity; } int get(int key) { if (mp.find(key) != mp.end()) { int res = (*mp[key]).second; l.erase(mp[key]); l.push_front(make_pa.

liudongshizhang的博客 216

电力远动入门:手把手解析IEC 60870-5-101规约的帧结构与报文交互(基于DL/T634.5101-2002)

本文深入解析IEC 60870-5-101规约的帧结构与报文交互,适用于电力远动通信系统。通过详细讲解规约的基础架构、控制域位定义及典型报文交互流程,帮助工程师快速掌握101规约的核心技术,提升电力自动化系统的调试与维护能力。

weixin_27076351的博客 244

Spring AI 项目实战(十):Spring Boot + AI + DeepSeek 构建智能合同分析技术实践(附完整源码)

摘要:基于Spring AI的智能合同审核系统开发 本文介绍了基于Spring Boot 3.2.0和Spring AI 1.0.0-M4构建的智能合同审核系统。系统采用分层架构设计,整合DeepSeek API实现文档解析、条款提取和风险分析功能。核心技术栈包括Spring AI、H2数据库、Apache POI/PDFBox等文档处理工具,实现了合同条款语义分析、异常识别和审核报告自动生成。项目解决了传统人工审核效率低、主观性强等问题,为合同管理提供了智能化解决方案。文章详细阐述了系统架构设计、技术选型

博客 653

【算法】【LRU】146. LRU缓存机制

Description 设计和实现一个LRU(最近最少使用)缓存数据结构,使它应该支持以下操作: get 和 put 。 get(key) - 如果密钥存在于缓存中,则获取密钥的值(值总是正数),否则返回 -1。 put(key, value) - 如果密钥不存在,请设置或插入值。当缓存达到其容量时,它应该在插入新项目之前使最近最少使用的项目作废。 后续: 你是否可以在 O(1) 时间复...

wurlin的博客 3661

【python科研数据处理】将Endnote自动搜索的所有pdf文件,全都移动指定文件夹中

将Endnote自动搜索到的全部pdf文件,全都移动指定文件夹中1 背景2 问题解决 手动反爬虫,禁止转载:原博地址 https://blog.csdn.net/lys_828/article/details/122370892(优快云博主:Be_melting) 知识梳理不易,请尊重劳动成果,文章仅发布在优快云网站上,在其他网站看到该博文均属于未经作者授权的恶意爬取信息 1 背景 在进行期末考试周后,面对最后一门功课,需要提交至少80篇SCI参考文献,因此最快下载文献的方式就是通过Web of S

lys_828的博客 1826

LeetCode:146. LRU 缓存机制(中等)

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

qq_42147969的博客 242

基于Python的网贷平台数据爬虫实战:Scrapy+Selenium+反反爬策略

python复制下载# items.py本文详细介绍了如何使用Python构建一个完整的网贷平台数据爬虫系统,涵盖了从基础爬取到高级反反爬策略的全套解决方案。我们使用了Scrapy框架作为基础,结合Selenium处理动态内容,实现了多种反反爬策略,并探讨了分布式爬虫的实现方式。机器学习识别验证码基于深度学习的网页结构变化检测自动化行为模拟的更精细控制基于Kubernetes的弹性爬虫集群。

2201_76125261的博客 1560

【数据分析】基于多组学数据整合的微生物与宿主互作网络构建及可视化分析

综上所述,本教程通过详细的步骤和方法,展示了如何整合微生物群落数据、宿主基因表达数据和代谢组数据,构建微生物与宿主互作网络,并进行可视化分析。这种方法为研究微生物与宿主之间的复杂关系提供了一种有力的工具,有助于推动相关疾病的研究和治疗。然而,在实际应用中,需要注意数据处理和分析过程中的各种问题,并结合实验验证来提高研究结果的可靠性和科学性。未来,随着多组学技术的不断发展和完善,以及数据分析方法的创新,相信我们能够更深入地理解微生物与宿主之间的互作机制,为疾病的预防、诊断和治疗提供更有力的支持。

专注生信领域 370

LeetCode腾讯50题-Day12-146/148/155

LeetCode50题(17天)-Day12 146 LRU缓存机制 题号:146 难度:中等 https://leetcode-cn.com/problems/lru-cache/ 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。 写入数据 put(key, value) - 如果密钥不存在,则

weixin_43760925的博客 286

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

LeetCode 146. LRU 缓存机制(LRU Cache)

易错点正确做法说明更新数据未移动位置保证“最近使用”put 超过容量未淘汰使用删除头部get 不存在时返回错误返回-1使用是 Python 实现 LRU 的最简洁且效率最高的方式。同时掌握哈希表 + 双向链表手动实现 LRU 也是面试时加分项。本题考查的是缓存机制 + 数据结构的组合使用,属于高频面试题之一。错误点正确方式删除时未断开前后节点_remove()正确处理 prev/next忘记从cache删除淘汰节点双向链表头尾更新顺序错误始终更新 prev/next 的双向性。

2501_91641025的博客 1069

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Java实现 LeetCode 146 LRU缓存机制

146. LRU缓存机制 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。 写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数...

南 墙 1万+

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

力扣146:LRU缓存

LRU缓存(Least Recently Used Cache)是一种常见的缓存淘汰策略,用于在缓存空间不足时决定移除哪些数据。优先淘汰最近最少使用的数据,保留最近频繁访问的数据。举个例子:安卓手机都可以把软件放到后台运行,比如我先后打开了「设置」「手机管家」「日历」,那么现在他们在后台排列的顺序是这样的:但是这时候如果我访问了一下「设置」界面,那么「设置」就会被提前到第一个,变成这样:假设我的手机只允许我同时开 3 个应用程序,现在已经满了。

yk_18的博客 756

【每日算法】LeetCode 146. LRU 缓存机制

摘要:LRU缓存机制的设计与实现 本文详细介绍了LeetCode 146题LRU缓存的设计实现。LRU(最近最少使用)缓存需要支持O(1)时间复杂度的get和put操作,并在容量满时淘汰最久未使用的数据。文章分析了两种主要实现方案:基于ES6 Map的简洁实现和经典的哈希表+双向链表实现。前者代码简洁但隐藏底层原理,后者能更好展示缓存机制原理但实现复杂。本文还对比了两种方案的优缺点,并列举了LRU在前端开发中的实际应用场景,如浏览器缓存和Vue的keep-alive组件。掌握LRU实现有助于前端开发者深入理

LYFlied的博客 691

LeetCode 146 LRU缓存机制 python

题目描述 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。 写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最...

孤行 1499

力扣hot100:146. LRU 缓存

我们需要维护一个时间的长短,以便于取出离现在最长的时间,这个时间比较容易实现,我们维护一个time表示当前时间,从0开始,然后在使用的一些关键字里面,当一个关键字使用的时间越小,那么它越久未被使用,我们只需要维护一个关键字使用的最小值就行,并且还需要有更新操作。,因此我们可以只使用一个哈希表,来同时维护这两个信息。来查询的,而查询只需要判断。听说华为实习笔试考了这题。由于结点和值都是通过。

m0_63997099的博客 1331

leetcode 146——C++简单实现LRU缓存机制

LRU缓存机制LRU缓存机制1、题目2、思路3、题解 LRU缓存机制 1、题目 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。 写入数据 put(key, value) -如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前

JMW1407的博客 2585

leetcode146、OrderedDict与lru_cache

本文探讨了Python中实现LRU缓存的两种方法:使用OrderedDict和哈希表+双向链表。首先介绍了leetcode146题LRU缓存的OrderedDict解法,该结构通过move_to_end和popitem方法自然契合LRU思想。然后分析了Python字典(dict)在3.6版本后实现的有序性特性,并指出其与OrderedDict的区别。最后深入研究了标准库functools.lru_cache的实现细节,展示了其采用哈希表+双向链表的方案,包括缓存命中和未命中时的处理逻辑、线程安全机制等核心实

usiel的博客 1022

【力扣算法】146-LRU缓存机制

题目 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。 写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使...

ZeromaXHe的博客 1701
上一篇: Leetcode 中等:95. 不同的二叉搜索树II
下一篇: 一星级挑战:09 打渔还是晒网
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青少年编程小助手_Python

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值