146. LRU缓存机制
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据get
和 写入数据put
。
获取数据get(key)
- 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
写入数据put(key, value)
- 如果密钥已经存在,则变更其数据值;如果密钥不存在,则插入该组「密钥/数据值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
进阶:
你是否可以在 O(1) 时间复杂度内完成这两种操作?
class LRUCache {
class Node {
Node last;
Node next;
Integer key;
Integer value;
public Node() {}
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
class DList {
Node head;
Node tail;
public void add(Node node) {
if(head == null) {
head = node;
tail = node;
}else {
tail.next = node;
node.last = tail;
tail = tail.next;
}
}
public Node removeHead() {
Node res = head;
if(head == tail) {
head = null;
tail = null;
}else {
head = head.next;
head.last = null;
}
return res;
}
public void moveToTail(Node node) {
if(node == tail) {
return;
}
if(head == node) {
add(removeHead());
return;
}
node.last.next = node.next;
node.next.last = node.last;
add(node);
}
}
private HashMap<Integer, Node> map;
private int capacity;
private DList list;
public LRUCache(int capacity) {
this.capacity = capacity;
map = new HashMap<>();
list = new DList();
}
public int get(int key) {
if(map.containsKey(key)) {
Node node = map.get(key);
list.moveToTail(node);
return node.value;
}else {
return -1;
}
}
public void put(int key, int value) {
if(map.containsKey(key)) {
Node node = map.get(key);
node.value = value;
list.moveToTail(node);
}else {
if(this.capacity == map.size()) {
Node node = list.removeHead();
map.remove(node.key);
}
Node node = new Node(key, value);
list.add(node);
map.put(key, node);
}
}
}