Skip to main content

146. LRU Cache

https://leetcode.com/problems/lru-cache/

Python

Built-in OrderedDict

from collections import OrderedDict


class LRUCache:
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.cap = capacity

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:
self.cache.move_to_end(key)
self.cache[key] = value

if len(self.cache) > self.cap:
self.cache.popitem(last=False)

Javascript

class ListNode {
constructor(key, value) {
this.value = value === undefined ? -1 : value;
this.key = key === undefined ? -1 : key;
this.next = null;
this.prev = null;
}
}
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.capacity = capacity;
this.size = 0;
this.map = {};
this.list = new LinkedList();
};

/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
if (this.map[key]) {
const node = this.map[key];
this.list.moveToFront(node);
return node.value;
} else {
return -1;
}
};

/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
if (this.map[key]) {
const node = this.map[key];
node.value = value;
this.list.moveToFront(node);
} else {
if (this.size === this.capacity) {
const last = this.list.removeLast();
delete this.map[last.key];
this.size -= 1;
}

const node = new ListNode(key, value);
this.list.insertNode(node);
this.map[key] = node;
this.size += 1;
}
};

class LinkedList {
constructor() {
this.head = new ListNode();
this.tail = new ListNode();

this.head.next = this.tail;
this.tail.prev = this.head;
}

insertNode(node) {
node.next = this.head.next;
this.head.next.prev = node;

node.prev = this.head;
this.head.next = node;

}

removeNode(node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}

moveToFront(node) {
this.removeNode(node);
this.insertNode(node);
}

removeLast() {
const last = this.tail.prev;
this.removeNode(last);
return last;
}
}