LRU(最近最少使用缓存结构) 通过使用Map()数据类型实现
(重点) Map类型的实例会维护键值对的插入顺序,所以可以根据插入顺序进行迭代操作。
//LRUCache构造函数,capacity(初始容量)
var LRUCache = function (capacity) {
this.map = new Map();
this.capacity = capacity;
};
get方法通过删除已存在的键值对,并重新插入键值对完成更新(新插入的键值对会按照顺序在最后一位)。
//定义get方法
LRUCache.prototype.get = function (key) {
if (!this.map.has(key)) return -1
let value = this.map.get(key)
this.map.delete(key)
this.map.set(key, value)
return value
};
put方法判断插入的键是否存在,存在即删除再插入,如果map.size===capacity也就是容量满了,通过keys()将map的所有键转换为数组形式,通过迭代器iterator可next()往下迭代一次,返回一个对象{done:false,value:本次迭代的value},通过value取值。
//定义get方法
LRUCache.prototype.put = function (key, value) {
if (this.map.has(key)) {
this.map.delete(key);
}
if (this.map.size === this.capacity) {
this.map.delete(this.map.keys().next().value)
}
this.map.set(key, value)
// if (this.map.has(key)) {
// }
};
完整代码如下:
/**
* @param {number} capacity
*/
//LRUCache构造函数
var LRUCache = function (capacity) {
this.map = new Map();
this.capacity = capacity;
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function (key) {
if (!this.map.has(key)) return -1
let value = this.map.get(key)
this.map.delete(key)
this.map.set(key, value)
return value
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function (key, value) {
if (this.map.has(key)) {
this.map.delete(key);
}
if (this.map.size === this.capacity) {
this.map.delete(this.map.keys().next().value)
}
this.map.set(key, value)
// if (this.map.has(key)) {
// }
};
/**
* 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)
*/