这道题目主要通过双向链表,加映射表去实现。具体实现代码如下,思路可以参考这篇文章
/**
* 实现节点
* @param {*} k
* @param {*} v
*/
let Node = function(k, v) {
this.key = k;
this.val = v;
this.next = null;
this.prev = null;
}
/**
* 实现双向链表
*/
let DoubleList = function() {
this.head = new Node(0,0)
this.tail = new Node(0,0)
this.size = 0;
this.head.next = this.tail;
this.tail.prev = this.head;
}
DoubleList.prototype.addLast = function(x) {
x.prev = this.tail.prev;
x.next = this.tail;
this.tail.prev.next = x
this.tail.prev = x;
this.size ++;
}
DoubleList.prototype.remove = function(x) {
x.prev.next = x.next;
x.next.prev = x.prev;
this.size--;
}
DoubleList.prototype.removeFirst = function() {
if (this.head.next == this.tail)
return null;
var first = this.head.next;
this.remove(first);
return first;
};
DoubleList.prototype.size = function() {
return this.size;
};
/**
* 实现Least Recently Cache
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.map = new Map();
this.cache = new DoubleList();
this.cap = capacity;
this.makeRecently = function(key) {
let x = this.map.get(key);
this.cache.remove(x);
this.cache.addLast(x);
}
this.addRecently = function(key, val) {
let x = new Node(key, val);
this.cache.addLast(x);
this.map.put(key, x);
}
this.addRecently = function(key, val) {
let x = new Node(key, val);
this.cache.addLast(x);
this.map.set(key, x);
};
this.deleteKey = function(key) {
let x = this.map.get(key);
this.cache.remove(x);
this.map.delete(key);
}
this.removeLeastRecently = function() {
let deletedNode = this.cache.removeFirst();
let deletedKey = deletedNode.key
this.map.delete(deletedKey)
}
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
if(!this.map.has(key)) {
return -1;
}
this.makeRecently(key);
return this.map.get(key).val;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, val) {
if(this.map.has(key)) {
this.deleteKey(key);
this.addRecently(key, val);
return
}
if(this.cap === this.cache.size) {
this.removeLeastRecently();
}
this.addRecently(key, val)
};