题解 | #设计LRU缓存结构#
设计LRU缓存结构
https://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84
/**
* @param {number} capacity
*/
var Solution = function (capacity) {
this.capacity = capacity;
// 使用map数据结构构造
this.map = new Map();
};
/**
* @param {number} key
* @return {number}
*/
Solution.prototype.get = function (key) {
// write code here
// get分为可以获取到和获取不到
if (this.map.has(key)) {
// 如果存在这个key,将value获取出来
let value = this.map.get(key);
// 删除原本位置的key
this.map.delete(key);
// 将最新的key放在map的最后
this.map.set(key, value);
return value
} else {
return -1;
}
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
Solution.prototype.set = function (key, value) {
if (this.map.has(key)) {
this.map.delete(key)
}
this.map.set(key, value);
if (this.map.size > this.capacity) {
let last = Array.from(this.map.keys())[0]
this.map.delete(last);
}
};
module.exports = {
Solution: Solution,
};
/**
* Your Solution object will be instantiated and called as such:
* var solution = new Solution(capacity)
* var output = solution.get(key)
* solution.set(key,value)
*/
#算法#


