题目:
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.
The cache is initialized with a positive capacity.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
import java.util.HashMap;
public class LRUCache {
class Node {
public int key;
public int value;
public Node next;
public Node pre;
public Node(){
}
public Node(int key, int value){
this.key = key;
this.value = value;
}
}
private Node head;
private Node tail;
private HashMap<Integer, Node> map;
private int capacity;
private int count;
public LRUCache(int capacity) {
map = new HashMap<>();
this.capacity = capacity;
this.count = 0;
head = new Node();
tail = new Node();
head.pre = null;
tail.next = null;
head.next = tail;
tail.pre = head;
}
public int get(int key) {
Node node = map.get(key);
if (node == null)
return -1;
deleteNode(node);
addToHead(node);
return node.value;
}
public void put(int key, int value) {
Node node = map.get(key);
if (node == null){
Node newNode = new Node();
newNode.key = key;
newNode.value = value;
addToHead(newNode);
map.put(key, newNode);
count++;
if (count > capacity){
Node tailNode = popTail();
map.remove(tailNode.key);
count--;
}
}else {
node.value = value;
deleteNode(node);
addToHead(node);
}
}
private void addToHead(Node node){
node.pre = head;
node.next = head.next;
head.next.pre = node;
head.next = node;
}
private void deleteNode(Node node){
Node pre = node.pre;
Node next = node.next;
pre.next = next;
next.pre = pre;
}
private Node popTail(){
Node node = tail.pre;
deleteNode(node);
return node;
}
public void print(){
Node node = head.next;
while (node.next != null){
System.out.print("(" + node.key +", " + node.value + ")" + "=>");
node = node.next;
}
System.out.println("NULL");
}
public static void main(String[] args) {
LRUCache cache = new LRUCache(2);
cache.put(1, 1);
cache.print();
cache.put(2, 2);
cache.print();
System.out.println(cache.get(1));
cache.print();
cache.put(3, 3);
cache.print();
System.out.println(cache.get(2));
cache.print();
cache.put(4, 4);
cache.print();
System.out.println(cache.get(1));
cache.print();
System.out.println(cache.get(3));
cache.print();
System.out.println(cache.get(4));
cache.print();
}
}