【leetcode】146. LRU缓存机制

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

https://leetcode-cn.com/problems/lru-cache/

// 头文件
class LRUCache
{
public:
	LRUCache(int capacity);
	int get(int key);
	void put(int key, int value);

private:
	std::unordered_map<int, std::list<std::pair<int, int>>::iterator> table;
	std::list<std::pair<int, int>> lru;
	int capacity;

};
// https://leetcode-cn.com/problems/lru-cache/
// https://labuladong.gitbook.io/algo/shu-ju-jie-gou-xi-lie/lru-suan-fa
// 哈希表 + 双向链表
LRUCache::LRUCache(int capacity)
{
	this->capacity = capacity;
}


// std::unordered_map<int, std::list<std::pair<int, int>>::iterator> table;
// std::list<std::pair<int, int>> lru;

int LRUCache::get(int key)
{
	auto it = table.find(key); // std::list<std::pair<int, int>>::iterator 为啥不是这个类型?
	if (it != table.end())
	{
		lru.splice(lru.begin(), lru, it->second);// 找到了,将这个放在链表最前面
		return it->second->second;
	}
	return -1;
}

void LRUCache::put(int key, int value)
{
	auto it = table.find(key);
	if (it != table.end())
	{
		lru.splice(lru.begin(), lru, it->second); // 如果找到了就更新这个值
		it->second->second = value;
		return;
	}

	lru.emplace_front(key, value);
	table[key] = lru.begin();
	
	if (table.size() > capacity) // 取size不要用list::size() 在C++里这个方法可能不是O(1)的
	{
		table.erase(lru.back().first);
		lru.pop_back();
	}
}

list::splice的用法和 emplace

/*
list::splice实现list拼接的功能。将源list的内容部分或全部元素删除,拼插入到目的list。

函数有以下三种声明:
一:void splice ( iterator position, list<T,Allocator>& x );
二:void splice ( iterator position, list<T,Allocator>& x, iterator it );
三:void splice ( iterator position, list<T,Allocator>& x, iterator first, iterator last );

解释:
position 是要操作的list对象的迭代器
list&x 被剪的对象

对于一:会在position后把list&x所有的元素到剪接到要操作的list对象(会将x全部裁切到list中,并且清空x,在position之前)
对于二:只会把it的值剪接到要操作的list对象中(只裁切一个元素)
对于三:把first 到 last 剪接到要操作的list对象中(裁切一个范围。x里需要被移动的元素的迭代器。区间为[first, last).)
*/
void splice()
{
	std::list<int> list1;
	std::list<int> list2 = { 10, 20 };
	std::list<int>::iterator it;

	for (int i = 1; i < 4; ++i)
	{
		list1.push_back(i); // 1 2 3 
	}
	it = list1.begin();
	++it; // point to 2


	list1.splice(it, list2); // 将list2的元素插入到it前面,清空list2的元素
	printList(list1); // 1 10 20 2 3
	printList(list2); // empty
#ifdef ALLOW_PRINT
	std::cout << *it << std::endl; // 2  还指向这个元素
#endif


	list2.splice(list2.begin(), list1, it); 
	printList(list1); // 1 10 20 3
	printList(list2); // 2
	// 此时it迭代器失效了???但是还能打印值
#ifdef ALLOW_PRINT
	std::cout << *it << std::endl; // 2 
#endif


	it = list1.begin();
	advance(it, 2); // 迭代器递增函数,it指向20
	list1.splice(list1.begin(), list1, it, list1.end());
	printList(list1); // 20 3 1 10

	it = list1.begin();
	advance(it, 2); // it指向1
	std::list<int>::iterator it2 = list2.end();
	list2.splice(list2.end(), list1, it, list1.end()); // 插入的位置可以是end()迭代器
	printList(list1); // 20 3
	printList(list2); // 2 1 10
}

// 当调用push或insert成员函数时,我们将元素类型的对象传递给它们,这些对象被拷贝到容器中。
// 而当我们调用一个emplace成员函数时,则是将参数传递给元素类型的构造函数。emplace成员使用这些参数在容器管理的内存空间中直接构造元素。
// emplace相关函数可以减少内存拷贝和移动。当插入rvalue,它节约了一次move构造,当插入lvalue,它节约了一次copy构造。
void emplace()
{
	std::list<int> list1 = { 1, 2, 3, 4, 5 };
	list1.emplace(list1.begin(), 222);
	printList(list1); // 222 1 2 3 4 5

	list1.emplace_back(333);
	printList(list1); // 222 1 2 3 4 5 333
	
	list1.emplace_front(111);
	printList(list1); // 111 222 1 2 3 4 5 333
}

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

相关推荐

LeetCode 146 - LRU缓存机制

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

互联网架构师笔记 1151

leetcode_146. LRU缓存机制

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

qq_37292201的博客 300

MATLAB实战:蓝牙GFSK调制解调全流程解析(附误码率优化技巧)

本文深入解析了蓝牙GFSK调制解调在MATLAB中的全流程实现,包括高斯滤波器设计、调制解调技术及误码率优化技巧。通过实战案例和代码示例,帮助工程师提升蓝牙通信系统的性能表现,特别是在降低误码率方面的有效方法。

weixin_29046035的博客 277

LEETCODE146 LRU缓存机制

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

lilinfei001的博客 252

【没有网络,安装python包】如何从 PyPI 下载并安装 Plotly 的离线包

在某些情况下,您可能需要在没有互联网连接的环境中安装 Python 包,例如在飞机上、在某些受限制的网络环境中或在需要离线安装的场景下。以下是如何在 PyPI(Python Package Index)下载 Plotly 包并进行离线安装的详细步骤。

赖德发的博客 1102

海鸥派OpenEuler开发板实战:从烧写到SSH连接的完整指南

本文提供海鸥派OpenEuler开发板从开箱到SSH远程连接的完整实战指南。详细介绍了基于海思SD3403/SS928芯片的算力开发板系统烧写、存储扩容、网络配置等关键步骤,帮助开发者快速上手这款AI边缘计算设备,并实现高效的远程开发与管理。

ruby5的博客 1120

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

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

2501_91641025的博客 1069

(详细教程)opencv+pycharm+笔记本摄像头 做一个人脸识别

文章目录 前言 一、pandas是什么? 二、使用步骤 1.引入库 2.读入数据 总结 一、安装opencv-python 这里推荐使用pycharm直接安装opencv-python 打开文件——设置——python解释器——点击+号 搜索opencv-python,点击安装包,等待片刻即可安装好 检查是否安装好,新建一个项目输入以下代码,若无报错则安装好 import cv2 二、准备分类器 咱们使用opencv官方提供的分类器,包括面部识别,侧...

qq_52852432的博客 1万+

【力扣LeetCode】146 LRU 缓存机制

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

Jiewang的博客 240

一条时间轴上的商品供给:商品供给域事件全景、八大子域事件清单与事件契约规范的工程推演

本文以虚构连锁零售企业“青禾鲜市”为例,用事件风暴重新梳理商品供给域:先剖析同词异义、状态模糊、隐式依赖与被动兜底四类冲突,再以时间轴、八条子域泳道与关键事件铺出全景地图,确立一个事件只有一个户口;随后为总店商品、门店商品、价格、库存、质量、标签、变更通知与操作日志列出聚合、事件、命令与策略,并统一命名、信封结构、版本与幂等规范。程序体检把初稿14个问题清零,仿真显示按聚合版本号更新可售视图可将误判从两位数百分比降到0.019%。文末给出四轮工作坊节奏与新品引入、全国调价、批次召回走查剧本。

曾经“等你生日那天”都遥远得像未来,如今却可欢愉的挥手说“下个十年见” 5万+

KNN算法

其原理是在给定的数据集中,根据某个距离度量方法,将测试数据与已知数据集中的所有数据进行距离计算,然后选取K个距离最近的数据作为测试数据的邻居,根据邻居的类别进行投票,将测试数据分类到得票最多的类别中。总之,KNN算法是一种简单而有效的分类方法,它不需要对数据进行训练,可以适用于多种数据类型和应用场景,并且可以通过调整K值或距离阈值等参数来控制算法的复杂度和性能。,KNN算法需要找到K个距离测试样本最近的训练样本,计算它们的类别,并将测试样本归入到得票最多的类别中。则取值为1,否则为0,表示邻居中属于类别。

优快云XXCQ的博客 2628

力扣-146.LRU缓存机制

小结:通俗地讲,LRU就是一个长度固定的队列,满了之后新的会把老的挤出去,特别的地方在于查询或修改操作,要把这个元素删掉重新插入,使用了这个元素就好像它是最近添加的新元素。,可以比较方便地删除旧元素。是有序的,可以直接通过。

weixin_46878941的博客 621

【AI】获取各类AI大模型api-key的快速教程(OpenAI、Gemini、Claude、DeepSeek)

【AI】获取各类AI大模型api-key的快速教程(OpenAI、Gemini、Claude、DeepSeek)

funfan的博客 2922

力扣leetcode第146题LRU缓存机制

使用HashMap+双链表的方式实现。 使用HashMap可以在O(1)的时间查询到缓存key,使用双链表是因为插入的时候要在头部插入,删除最少使用的key需要尾部删除。 import java.util.HashMap; import java.util.Map; class LRUCache { /** * ["LRUCache","put","put","put","put","get","get","get","get","put","get","get","g..

u010523770的专栏 304

撸毛笔记-电信营业厅 v5.03

电信营业厅 v5.03签到和完成部分金豆任务, 喂宠物7天,15天,28天连签抽奖, 宠物等级权益兑换自己设置电信的服务密码, 把 手机号#服务密码 填到变量里:每天运行一两次const $ = new Env("电信营业厅");

xiaoshun007的专栏 4494

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

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

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

LYFlied的博客 691

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

Java实现 LeetCode 146 LRU缓存机制

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

南 墙 1万+

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

深度学习工具包 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")

LeetCode 146 LRU缓存机制 python

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

孤行 1499

Leetcode 146. LRU缓存机制 解题思路及C++实现

解题思路: 使用一个双向链表存储最常使用的key value对,最近使用的元素放在链表的表头,链表中最后一个元素是使用频率最低的元素。同时,使用一个map来记录对应的<key,<key, value>>,用于查找现在的缓存中是否有key及其value。 class LRUCache { public: int n; list<pair&l...

PaniniGu的博客 680

LeetCode 146. LRU缓存机制

【代码】LeetCode 146. LRU缓存机制。

qq_45972928的博客 306

精选力扣500题 第2题 LeetCode 146. LRU 缓存机制 【c++详细题解】

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

林深不见鹿 的博客 783

[LeetCode] 146、LRU缓存机制

题目描述 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。(最近最少使用 LRU:Least Recently Used的缩写) 要求:在O(1)O(1)O(1)时间复杂度内完成这两种操作? 解题思路 巨佬题解(一定要看,好到炸!)。本题的核心就是设计一个数据结构,我们可以总结出 cache 这个数据结构必...

aift的专栏 253

LeetCode-146.LRU缓存机制

LeetCode-146.LRU缓存机制 今天刷leetcode刷到非常有意思的题,让自己设计和实现一个LRU缓存机制,并且让在O(1)的时间复杂度完成。 题目链接 https://leetcode-cn.com/problems/lru-cache/ 首先了解一下LRU缓存机制,可参考这篇文章漫画:什么是LRU算法? 题目截图 解题思路 由于要求O(1)的复杂度,就需要用...

斑布点月 235

力扣第206题反转链表和第146LRU缓存机制

题目: 思路: 1.定义三个指针,分别为反转后newHead,当前头指针cur和下一个指针next 2.将反转的newHead初始换,然后让反转后的指针代表的值赋值给cur.next 3.然后循环,当next为空时结束循环 classSolution{ publicListNodereverseList(ListNodehead){ if(head==null) returnhead; ListNodene...

qq_57605078的博客 454
上一篇: ureal engine 4.25.0安装过程
下一篇: 【leetcode】222. 完全二叉树的节点个数(附加 求完全二叉树叶子节点个数)
eclipse_c
博客等级 码龄14年 28粉丝 162原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值