题解 | #设计LRU缓存结构#
设计LRU缓存结构
https://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84
class Node { constructor(key, value) { this.key = key; this.value = value; this.prev = null; this.next = null; } } /** * @param {number} capacity */ var Solution = function (capacity) { // write code here this.capacity = capacity; this.cache = new Map(); this.head = new Node(); this.tail = new Node(); this.head.next = this.tail; this.tail.prev = this.head; }; /** * @param {number} key * @return {number} */ Solution.prototype.get = function (key) { // write code here if (this.cache.has(key)) { const node = this.cache.get(key); this.moveToHead(node); return node.value; } else { return -1; } }; /** * @param {number} key * @param {number} value * @return {void} */ Solution.prototype.set = function (key, value) { // write code here if (this.cache.has(key)) { const node = this.cache.get(key); node.value = value; } else { if (this.cache.size === this.capacity) { const tailPrev = this.tail.prev; this.removeNode(tailPrev); this.cache.delete(tailPrev.key); } const newNode = new Node(key, value); this.cache.set(key, newNode); this.addToHead(newNode); } }; Solution.prototype.addToHead = function (node) { node.prev = this.head; node.next = this.head.next; this.head.next.prev = node; this.head.next = node; } Solution.prototype.removeNode = function (node) { node.prev.next = node.next; node.next.prev = node.prev; } Solution.prototype.moveToHead = function (node) { this.removeNode(node); this.addToHead(node); } 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) */
双向链表+哈希表实现