一、题目地址
https://leetcode-cn.com/problems/lru-cache/
二、具体代码
// 时间复杂度: O(1)
// 空间复杂度: O(n)
var ListNode = function(key,value){
this.key = key;
this.value = value;
this.next = null;
this.prev = null;
}
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
//总容量
this.capacity = capacity;
//双向链表
this.head = new ListNode();
this.tail = new ListNode();
this.head.next = this.tail;
this.tail.prev = this.head;
//储存键以及对应的node节点
this.map = new Map();
};
LRUCache.prototype.insertTail = function(node) {
this.tail.prev.next = node;
node.prev = this.tail.prev;
node.next = this.tail;
this.tail.prev = node;
}
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
if(!this.map.has(key)){
return -1;
}
let node = this.map.get(key);
//把最近使用过的node移到双向链表最后面
node.prev.next = node.next;
node.next.prev = node.prev;
//插入链表尾部
this.insertTail(node);
return node.value;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
if(this.map.has(key)){
//获取到node
let node = this.map.get(key);
//修改node的val
node.value = value;
//移到尾部
node.prev.next = node.next;
node.next.prev = node.prev;
this.insertTail(node);
}else{
//如果已经满了
if(this.map.size == this.capacity){
//删除链表最前面的节点
let rmNode = this.head.next;
this.head.next = this.head.next.next;
this.head.next.prev = this.head;
//删除map中对应的值
this.map.delete(rmNode.key);
}
let node = new ListNode(key,value);
this.map.set(key,node);
//插入链表尾部
this.insertTail(node);
}
};
/**
* 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)
*/
三、补充部分
关注公众号:【深漂程序员小庄】:
内含丰富的学习资源和面试经验(不限前端、java),还有学习交流群可加,并且还有各大厂大佬可一起交流学习,一起进步~添加小庄微信,回复【加群】,可加入互联网技术交流群: