package Interview;
import java.util.HashMap;
import java.util.Map;
/*
* 实现最近最少使用算法,且get,put时间复杂度为O(1)
* */
public class LRUCache {
private Map<Integer, DLinkedList> cache;
DLinkedList tail=null;
DLinkedList head=null;
int capacity;
public LRUCache(int capacity) {
// TODO Auto-generated constructor stub
cache=new HashMap<>();
this.capacity=capacity;
}
public int get(int key){
if (cache.containsKey(key)) {
DLinkedList target=cache.get(key);
int value=target.value;
target.update();
return value;
}else {
return -1;
}
}
public void set(int key,int value){
if(cache.containsKey(key)){
DLinkedList target=cache.get(key);
target.value=value;
target.update();
}else {
if(capacity==0) return;
if(cache.size()==capacity){
cache.remove(head.key);
head.removeFromHead();
}
DLinkedList newNode=new DLinkedList(key, value);
cache.put(key, newNode);
newNode.append();
}
}
class DLinkedList {
int key;
int value;
DLinkedList left=null;
DLinkedList right=null;
public DLinkedList(int key,int value) {
// TODO Auto-generated constructor stub
this.key=key;
this.value=value;
}
private void removeFromHead(){
if(tail==this){
head=null;
tail=null;
}else {
head=this.right;
head.left=null;
}
}
private void update(){
if(tail==this) return;
else {
if(this!=head){
this.left.right=this.right;
}else {
head=this.right;
}
this.right.left=this.left;
this.append();
}
}
private void append(){
if(tail==null){
head=this;
tail=this;
}else {
this.right=null;
this.left=tail;
tail.right=this;
tail=this;
}
}
}
}
public class LRUCache {
class Node{
int key,value;
Node next,prev;
public Node(int key,int val){
this.key=key;
this.value=val;
}
}
Map<Integer,Node>cache;
Node head;
int capacity ;
public void unlink(Node node){
node.next.prev=node.prev;
node.prev.next=node.next;
}
public LRUCache(int capacity) {
head=new Node(-1,-1);
head.next=head;
head.prev=head;
cache=new HashMap<>();
this.capacity=capacity;
}
public void addHead(Node node){
head.next.prev=node;
node.next=head.next;
head.next=node;
node.prev=head;
}
public Node removeTail(){
Node node=head.prev;
head.prev.prev.next=head;
head.prev=head.prev.prev;
return node;
}
public int get(int key) {
if(capacity==0)
return -1;
if(!cache.containsKey(key))
return -1;
else{
Node node=cache.get(key);
unlink(node);
addHead(node);
return node.value;
}
}
public void put(int key, int value) {
if(capacity==0) return;
if(cache.containsKey(key)){
Node node=cache.get(key);
unlink(node);
node.value=value;
addHead(node);
cache.put(key,node);
}else{
if(cache.size()==capacity){
Node removenode=removeTail();
cache.remove(removenode.key);
}
Node node=new Node(key,value);
addHead(node);
cache.put(key,node);
}
}
}