LRU Cache

LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

设计并实现一个最近最少使用的数据结构

Solution1

Double Linked List && Map

O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class LRUCache {
private int capacity;
private Node head = new Node(-1, -1);
private Node tail = new Node(-1, -1);
private Map<Integer, Node> map = new HashMap<>();

private class Node {
private Node prev;
private Node next;
private int key;
private int value;
public Node(int key, int value) {
this.key = key;
this.value = value;
this.prev = null;
this.next = null;
}
}

public LRUCache(int capacity) {
this.capacity = capacity;
this.head.next = tail;
this.tail.prev = head;
}

public int get(int key) {
if (!map.containsKey(key)) {
return -1;
}

Node current = map.get(key);
current.prev.next = current.next;
current.next.prev = current.prev;
moveToTail(current);
return current.value;
}

public void put(int key, int value) {
if (get(key) != -1) {
map.get(key).value = value;
return;
}

if (map.size() == capacity) {
map.remove(head.next.key);
head.next = head.next.next;
head.next.prev = head;
}

Node current = new Node(key, value);
map.put(key, current);
moveToTail(current);
}

private void moveToTail(Node current) {
current.prev = tail.prev;
current.next = tail;
tail.prev.next = current;
tail.prev = current;
}
}