146. LRU缓存机制(JS实现)

1 题目

运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
进阶:
你是否可以在 O(1) 时间复杂度内完成这两种操作?
示例:
LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 该操作会使得关键字 2 作废
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得关键字 1 作废
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4

2 思路

这道题的主要思路链表和哈希表来实现查找和插入删除的O(1)的时间复杂度

3代码

/**
 * @param {number} capacity
 */
var LRUCache = function(capacity) {
    this.capacity = capacity;
    this.listHead = null;
    this.listTail = null;
    this.map = {};
    this.len = 0;
};

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function(key) {
    let node = this.map[key];
    if (typeof node === 'object') {
        if (this.listTail !== node) {
            if (node.prev) {
                node.prev.next = node.next;
                node.next.prev = node.prev;
            } else {
                this.listHead = node.next;
                this.listHead.prev = null;
            }
            this.listTail.next = node;
            node.prev = this.listTail;
            node.next = null;
            this.listTail = node;
        }
        
        return node.val;
    } else {
        return -1;
    }
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function(key, value) {
    if (this.get(key) !== -1) {
        this.map[key].val = value;
        return;
    }

    let newNode = new Node(key, value);
    this.map[key] = newNode;
    if (this.len === this.capacity) {
        if (!this.listHead) return;
        delete this.map[this.listHead.key];
        this.listHead = this.listHead.next;
        if (this.listHead) this.listHead.prev = null;
        this.listTail.next = newNode;
        newNode.prev = this.listTail;
        this.listTail = newNode;
    } else {
        if (!this.listHead) {
            this.listHead = this.listTail = newNode;
        } else {
            this.listTail.next = newNode;
            newNode.prev = this.listTail;
            this.listTail = newNode;
        }
        this.len++;
    }
};

function Node(key, val) {
    this.key = key;
    this.val = val;
    this.next = null;
    this.prev = null;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
解法1:使用有序字典(OrderedDict) 思路: 1. 使用一个有序字典来存储缓存的键值对,有序字典可以保持插入顺序。 2. 当插入一个新的键值对时,如果缓存已满,需要删除最久未使用的键值对,即删除有序字典的第一个元素。 3. 当访问一个已存在的键值对时,需要将该键值对移动到有序字典的末尾,表示最近使用过。 实现: 1. 初始化时,设定缓存容量,创建一个空的有序字典。 2. 获取指定键的值时,若键不存在则返回-1;若键存在则将该键值对的值返回,并将该键值对移动到有序字典的末尾。 3. 插入一个键值对时,若键已存在则更新该键值对的值,并将该键值对移动到有序字典的末尾;若键不存在,则插入该键值对,并将该键值对移动到有序字典的末尾。若插入后缓存超出容量,则删除有序字典的第一个元素。 代码实现如下: ```python from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = OrderedDict() def get(self, key: int) -> int: if key in self.cache: self.cache.move_to_end(key) return self.cache[key] return -1 def put(self, key: int, value: int) -> None: if key in self.cache: del self.cache[key] self.cache[key] = value if len(self.cache) > self.capacity: self.cache.popitem(last=False) ``` 复杂度分析: - 时间复杂度:对于get和put操作,有序字典的删除和插入操作的时间复杂度都是O(1),因此 get和put操作的时间复杂度均为O(1)。 - 空间复杂度:使用了一个有序字典来存储键值对,因此空间复杂度为O(N),其中N为缓存的容量。 解法2:使用哈希表和双向链表 思路: 1. 使用一个哈希表来存储缓存的键值对,哈希表的键为缓存的键,值为双向链表中对应节点的指针。 2. 使用一个双向链表来存储缓存的键值对,链表的每个节点包括键、值和前后指针。 3. 当插入一个新的键值对时,如果缓存已满,需要删除最久未使用的键值对,即删除双向链表的头节点,同时从哈希表中删除该键。 4. 当访问一个已存在的键值对时,需要将该键值对对应的节点移动到双向链表的尾部,表示最近使用过。 实现: 1. 初始化时,设定缓存容量,创建一个空的哈希表和双向链表。 2. 获取指定键的值时,若键不存在则返回-1;若键存在则将该键值对的值返回,并将该键值对对应的节点移动到双向链表的尾部。 3. 插入一个键值对时,若键已存在则更新该键值对的值,并将该键值对对应的节点移动到双向链表的尾部;若键不存在,则插入该键值对对应的节点到双向链表的尾部,并在哈希表中添加该键值对。若插入后缓存超出容量,则删除双向链表的头节点,并从哈希表中删除对应键。 代码实现如下: ```python class DLinkedNode: def __init__(self, key=0, value=0): self.key = key self.value = value self.prev = None self.next = None class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = dict() self.head = DLinkedNode() self.tail = DLinkedNode() self.head.next = self.tail self.tail.prev = self.head def get(self, key: int) -> int: if key in self.cache: node = self.cache[key] self.moveToTail(node) return node.value return -1 def put(self, key: int, value: int) -> None: if key in self.cache: node = self.cache[key] node.value = value self.moveToTail(node) else: if len(self.cache) >= self.capacity: self.removeLRU() node = DLinkedNode(key, value) self.cache[key] = node self.addToTail(node) def moveToTail(self, node: DLinkedNode) -> None: self.removeNode(node) self.addToTail(node) def removeNode(self, node: DLinkedNode) -> None: node.prev.next = node.next node.next.prev = node.prev def addToTail(self, node: DLinkedNode) -> None: node.prev = self.tail.prev node.next = self.tail self.tail.prev.next = node self.tail.prev = node def removeLRU(self) -> None: lruNode = self.head.next self.removeNode(lruNode) del self.cache[lruNode.key] ``` 复杂度分析: - 时间复杂度:对于get和put操作,哈希表的查找和删除操作的时间复杂度都是O(1),双向链表的插入和删除操作的时间复杂度也是O(1),因此 get和put操作的时间复杂度均为O(1)。 - 空间复杂度:哈希表和双向链表分别需要存储所有键值对和节点,因此空间复杂度为O(N),其中N为缓存的容量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值