一、题目描述:
这是leetcode146题:LRU 缓存机制
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。 实现 LRUCache 类:
LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存 int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。 void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?
示例:
输入
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
输出
[null, null, null, 1, null, -1, null, -1, 3, 4]
解释
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1); // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
lRUCache.get(2); // 返回 -1 (未找到)
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
lRUCache.get(1); // 返回 -1 (未找到)
lRUCache.get(3); // 返回 3
lRUCache.get(4); // 返回 4
难度:中等
二、思路分析:
认真审题后,题目中提到key-value
键值对,我们就要想到哈希表,它的查询速度最快,时间复杂度为O(1)。
光用哈希表可以解决问题吗?答案是不行。哈希表是无序的,无法知道里面键值对哪些最近访问过,哪些很久没访问。
再继续读题,题目要求还有对数据插入删除操作:
- 之前有的,更新数据,刷新位置。
- 之前没有的,容量没超上限就直接写入,超过上限,就先删掉最久没有使用的数据,再写入。 题目要求还说get和put操作需要时间复杂度为O(1),因此选择双向链表。双向链表,当节点有前驱指针,删除和移动节点都是指针的变动,时间复杂度为O(1)。
三、AC 代码:
// 链表节点
class Node {
constructor(key, val) {
this.key = key;
this.val = val;
}
}
// 双链表
class DoubleList {
// 初始化头、尾节点、链表最大容量
constructor() {
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;
}
// 在链表头部添加节点
addFirst(node) {
node.next = this.head.next;
node.prev = this.head;
this.head.next.prev = node;
this.head.next = node;
this.size++;
}
// 删除链表中存在的node节点
remove(node) {
node.prev.next = node.next;
node.next.prev = node.prev;
this.size--;
}
// 删除链表中最后一个节点,并返回该节点
removeLast() {
// 链表为空
if (this.tail.prev == this.head) {
return null;
}
let last = this.tail.prev;
this.remove(last);
return last;
}
}
var LRUCache = function (capacity) {
this.cap = capacity;
this.map = new Map();
this.cache = new DoubleList();
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function (key) {
let map = this.map;
if (!map.has(key)) {
return -1;
}
let val = map.get(key).val;
// 最近访问数据置前
this.put(key, val);
return val;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function (key, value) {
let cache = this.cache;
let map = this.map;
let node = new Node(key, value);
if (map.has(key)) {
// 删除旧的节点,新的插到头部
cache.remove(map.get(key));
} else {
if (this.cap == cache.size) {
// 删除最后一个
let last = cache.removeLast();
map.delete(last.key);
}
}
// 新增头部
cache.addFirst(node);
// 更新 map 映射
map.set(key, node);
};
四、总结:
LRU缓存机制是到代码设计题,通过认真审题我们不难得出解决问题的算法思想,但代码实现的难度其实是很高的,需要手写“哈希表+双向链表”,因此我们还是需要多多练习!!
往后继续加油鸭,多刷leetcode,修炼内力~~
本文正在参与「掘金 3 月闯关活动」,点击查看活动详情