package com.test;
/**
* @author yourname
* Created on
*/
public class LRUCache {
// 相当于自己定义一个带时间限制的treeMap 比较大小通过最后一次访问时间来判断
// map的底层显然是用链表实现的
/*
1.put操作
遍历队列,看看是否已经存在这个key
如果已经存在,则找到位置并更新value,然后将该结点移至队列头
如果不存在
如果容量没满
直接头插
如果容量满了
直接更新队列尾结点的key和value,然后移动至表头
2.get操作
遍历队列,如果没找到,返回-1
如果找到了,返回value,并将该结点移至队列头
*/
class Node{
int key;
int value;
Node pre;
Node post;
Node(int key , int value){
this.key = key;
this.value = value;
pre = null;
post = null;
}
}
Node head;
Node trail;
private int capacity;
private int curCapacity;
public LRUCache(int capacity) {
this.capacity = capacity;
curCapacity = 0;
head = null;
trail = null;
}
public int get(int key) {
Node p = head;
while(p!=null){
if(key == p.key)
break;
p = p.post;
}
if(p!=null){
// 说明这个key已经存在
// 如果已经是表头,则无需移动
if(head != p){
// 将p移动至表头
Node q = p.post;
Node r = p.pre;
p.post = head;
p.pre = null;
r.post = q;// q可以为null
if(q!=null)
q.pre = r;
else
trail = r;
head.pre = p;
head = p;
}
return p.value;
}
else{
return -1;
}
}
public void put(int key, int value) {
if(curCapacity == 0){
Node node = new Node(key,value);
head = node;
trail = node;
curCapacity++;
return ;
}
Node p = head;
while(p!=null){
if(key == p.key)
break;
p = p.post;
}
if(p!=null){
// 说明这个key已经存在
p.value = value;
// 如果已经是表头,则无需移动
if(head != p){
// 将p移动至表头
Node q = p.post;
Node r = p.pre;
p.post = head;
p.pre = null;
r.post = q;// q可以为null
if(q!=null)
q.pre = r;
else
trail = r;
head.pre = p;
head = p;
}
}else{
// 不存在key,如果容量没满则直接头插
if(curCapacity < capacity){
Node node = new Node(key,value);
node.post = head;
head.pre = node;
head = node;
}else{
// 直接更新队尾,然后移至表头
trail.key = key;
trail.value = value;
trail.post = head;
head.pre = trail;
Node a = trail;
trail = trail.pre;
a.pre = null;
trail.post = null;
head = a;
}
curCapacity++;
}
}
public static void main(String[] args) {
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
System.out.println("null");
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
System.out.println(lRUCache.get(1));
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
System.out.println(lRUCache.get(2));
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
System.out.println(lRUCache.get(1));
System.out.println(lRUCache.get(3));
System.out.println(lRUCache.get(4));
}
}
LRUCache-Java实现
最新推荐文章于 2023-11-02 15:17:10 发布