设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作:
获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回-1。
写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。
要求get和put都为O(1)的时间复杂度。
输入描述:
第一行是两个整数N,M。代表共有N次操作,缓存容量为M,用空格分隔。 第2~n+1行是n次操作,格式为"PUT x y"或"GET x"。x和y为题面所要求的数字。、
输出描述:
对于每个GET操作,输出一行数字作为结果。
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int cache = Integer.valueOf(sc.nextLine().trim());
LRUCache lru = new LRUCache(cache);
String s;
while(sc.hasNext()){
s = sc.nextLine();
String[] ss = s.split(" ");
if("p".equals(ss[0]) && cache > 0){
int key = Integer.valueOf(ss[1]);
int value = Integer.valueOf(ss[2]);
lru.put(key, value);
}else if("g".equals(ss[0])){
if(cache <= 0){
System.out.println(-1);
}else{
int key = Integer.valueOf(ss[1]);
System.out.println(lru.get(key));
}
}
}
}
}
class LRUCache{
private class Node{
private Node next, pre;
private int key, value;
public Node() {
super();
}
public Node(int key, int value) {
super();
this.key = key;
this.value = value;
}
}
private int cache, count;
private Node head, tail;
private Map<Integer, Node> map;
private void addNode(Node node){
Node old = head.next;
head.next = node;
node.pre = head;
node.next = old;
old.pre = node;
}
private void removeNode(Node node){
Node previous = node.pre;
previous.next = node.next;
node.next.pre = previous;
}
private void moveToHead(Node node){
removeNode(node);
addNode(node);
}
private Node popTail(){
Node prev = tail.pre;
removeNode(prev);
return prev;
}
public LRUCache(int cache) {
super();
this.cache = cache;
this.count = 0;
map = new HashMap<>();
head = new Node();
tail = new Node();
head.next = tail;
tail.pre = head;
}
public int get(int key){
Node node = map.get(key);
if(node == null) return -1;
moveToHead(node);
return node.value;
}
public void put(int key, int value){
Node node = map.get(key);
if(node == null){
if(count == cache){
map.remove(popTail().key);
--count;
}
Node fresh = new Node(key, value);
map.put(key, fresh);
addNode(fresh);
count++;
}else{
node.value = value;
}
}
}