LRU算法:全称是 Least Recently Used,最久未使用。就是 “最长时间没使用的 优先删除”。 https://baike.baidu.com/item/LRU
内存缓存淘汰规则:当内存满了,把最久未使用的内容先淘汰。
就是比如有一个容器只能放5条数据,那么当放进5条数据后,再有新数据要存的时候,要先删掉一条才能存新数据,那么删掉谁呢?就是删掉最久未使用的那一条数据。
思路:
当访问一个数据时:
- 该数据不在容器中,则设置该数据放入容器的第一位。
- 已经存在于容器中,则将该数据的位置移到第一位。
- 当容器放满后,则将容器的最后一位数据移除。
如上图,访问数据 1 、2、3、4、2、3、5、6、7 时 容器中的数据存储变化。
- 一旦出现 键值对 想到 哈希表,因为他能在 O(1) 时间内通过键找到值
- 对于出入先后顺序问题 想到 栈 队列 链表
- 哈希表能实现 时间复杂度为O(1) 的 随机访问
- 链表可以快速移动节点的位置
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.max = capacity
this.cache = new Map()
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
if(this.cache.has(key)){
const val = this.cache.get(key)
this.cache.delete(key)
this.cache.set(key,val)
return val
}else{
return -1;
}
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
if(this.cache.has(key)){
this.cache.delete(key)
}else if(this.cache.size >= this.max){
this.cache.delete(this.cache.keys().next().value)
}
this.cache.set(key,value)
};
/**
* Your LRUCache object will be instantiated and called as such:
* var obj = new LRUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
class LRU {
constructor(capacity){
this.max = capacity
this.cache = new Map()
}
get(key){
if(this.cache.has(key)){
const val = this.cache.get(key)
this.cache.delete(key)
this.cache.set(key,val)
return val
}else{
return -1;
}
}
put(key ,value){
if(this.cache.has(key)){
this.cache.delete(key)
}else if(this.cache.size >= this.max){
this.cache.delete(this.cache.keys().next().value)
}
this.cache.set(key,value)
}
}