思考过程:
1.cache的长度确定。
2.get方法如果获取到数据则返回,获取不到则返回-1.
3.put方法如果长度超过限制则替换掉访问最少的值。这是否意味着需要有个计数?
4.如果有个计数来统计访问量,该如何保证时间复杂度是O(1)?
5.不如维护一个链表和一个map。利用map快速定位到链表中的元素,如果找到元素,则将对应链表元素放置道开头;调用put方法时可以快速利用
function Node(key, element) {
this.element = element;
this.key = key;
this.next = null;
this.prev = null;
}
function List() {
this.head = new Node("head", "head");
this.tail = this.head;
}
List.prototype.delete = function(item) {
if(item.next == null) {
item.prev.next = null;
this.tail = item.prev;
} else {
item.prev.next = item.next;
item.next.prev = item.prev;
}
}
List.prototype.push = function(item) {
if(this.head.next == null) {
this.head.next = item;
item.prev = this.head;
this.tail = item;
} else {
item.next = this.head.next;
item.next.prev = item;
item.prev = this.head;
this.head.next = item;
}
}
List.prototype.deleteTail = function() {
if(this.tail.prev == null) {
return false;
} else {
var oldTail = this.tail;
var prevNode = this.tail.prev;
prevNode.next = null;
this.tail = prevNode;
}
return oldTail;
}
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.capacity = capacity;
this.cache = new List();
this.map = {};
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
if(this.map[key]) {
this.cache.delete(this.map[key]);
this.cache.push(this.map[key]);
return this.map[key].element;
}
return -1;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
// if key exist
if(this.map[key]) {
this.cache.delete(this.map[key]);
} else if(Object.keys(this.map).length >= this.capacity) {
var tail = this.cache.deleteTail();
delete this.map[tail.key];
}
this.map[key] = new Node(key, value);
this.cache.push(this.map[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)
*/