Comments (3)
LRU缓存
- 每次被使用时,数据成为最新的数据
- 容量满了时,淘汰最久未被使用的数据
- 新增的数据为最新
- 每次被get到的数据也是最新
我们先考究一下操作
- Constructor(capacity)。构造函数,允许设置缓存容量。
- put(key, value)。放入数据,若存在,则更新value值
- get(key)。获取数据
如果我们维护一个数组。则涉及到数组的几个操作
- 查找。get或者put时,要根据key值查找到对应的value,数组的查找O(n)
- 删除。如果容量满了,会有删除操作O(n)
所以单纯的用数组也不行。那我用一个额外的空间缓存数据呢(空间换时间)?
用一个map来记录每个key对应数组的index
那么每次put和get的时候也更新一下map。
这个方法挺不错的,查找的时间效率可以降为O(1)。但是删除还是那么慢O(n),因为数组的特性,这里就要考虑换一下数据结构了。
链表的查找为O(n) 删除为O(1)
因为上面我们讲了,如果用一个map来存当前操作到的一些状态,那么可以把查询的时间降低,那么这个方法是否也适用于链表呢?
是的
比如我们在map中已经有(key, node)。在put的时候,就可以快速定位到一个node。因此这里我们的map需要存node信息。
但是又有另外一个麻烦。
单链表删除,已知链表和node,还是得遍历一次链表
因此,我们需要用双链表,因为双链表中的node保存了前后信息,删除时不需要遍历整个链表,真正的又快又好。
至此,我们利用一个map存储每个活动节点,把遍历操作改为了查map的操作,同时,由于map内存储的节点是双向指针,那么不管是增加和删除,时间复杂度都是O(1)
而对于map而言,set、has、get操作都是O(1),因此整体结果
- 时间复杂度 O(1) -> get、put
- 空间复杂度 O(n) -> get、put
from basic-programming-knowledge.
厉害了,大佬
from basic-programming-knowledge.
leetcode 460
from basic-programming-knowledge.
Related Issues (20)
- 【笔记】重读EventLoop HOT 2
- webpack原理
- 2021-11-25 图论
- 【VIM】编辑器相关整理
- 【Rust】资源汇总
- 【React】资源汇总
- 【tools】最有用的那些软件、站点-工具链
- 【英语】学习资源
- 【vim】文艺复兴·VIM使用指南·Day 1
- 【vim】文艺复兴·VIM使用指南·Day 2
- 【vim】文艺复兴·VIM使用指南·Day 3
- 【翻译】monio关于monad的解释
- 【函数式编程】函子 HOT 1
- 【异步】async/await比Promise好吗?
- 【杂文】述职报告的思考
- 【函数式编程】什么是lambda演算? HOT 1
- 【函数式编程】haskell语言-haskell趣学指南 HOT 5
- 【工程化】如何创建一个现代化的前端基础库
- wsl2开发环境设置排坑
- 前端库
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from basic-programming-knowledge.