实现LRU缓存机制以解决LeeCode146问题
实现了一个基于哈希表和双向链表的LRU(最近最少使用)缓存机制。该机制通过在双向链表的尾部添加最近使用的元素,并从头部移除最近最少使用的元素,以维护一个固定大小的缓存。当缓存满时,通过移除头部元素来腾出空间。此实现支持get和put操作,符合LRU缓存策略的要求。
This commit is contained in:
parent
625832361c
commit
32a8ad89b9
@ -9,8 +9,7 @@ import java.util.HashMap;
|
|||||||
public class LeeCode146 {
|
public class LeeCode146 {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void test()
|
public void test() {
|
||||||
{
|
|
||||||
LRUCache lruCache = new LRUCache(2);
|
LRUCache lruCache = new LRUCache(2);
|
||||||
lruCache.put(1, 1);
|
lruCache.put(1, 1);
|
||||||
lruCache.put(2, 2);
|
lruCache.put(2, 2);
|
||||||
@ -39,7 +38,7 @@ public class LeeCode146 {
|
|||||||
this.after = after;
|
this.after = after;
|
||||||
}
|
}
|
||||||
|
|
||||||
public EntryNode(Integer key ,Integer object) {
|
public EntryNode(Integer key, Integer object) {
|
||||||
this.key = key;
|
this.key = key;
|
||||||
this.object = object;
|
this.object = object;
|
||||||
}
|
}
|
||||||
@ -48,7 +47,7 @@ public class LeeCode146 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
HashMap<Integer,EntryNode> caches;
|
HashMap<Integer, EntryNode> caches;
|
||||||
EntryNode head;
|
EntryNode head;
|
||||||
EntryNode tail;
|
EntryNode tail;
|
||||||
Integer size = null;
|
Integer size = null;
|
||||||
@ -90,7 +89,7 @@ public class LeeCode146 {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
EntryNode v = new EntryNode(key,value);
|
EntryNode v = new EntryNode(key, value);
|
||||||
caches.put(key, v);
|
caches.put(key, v);
|
||||||
addNode(v);
|
addNode(v);
|
||||||
if (caches.size() > size) {
|
if (caches.size() > size) {
|
||||||
@ -103,6 +102,7 @@ public class LeeCode146 {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 删除某个节点
|
* 删除某个节点
|
||||||
|
*
|
||||||
* @param entryNode
|
* @param entryNode
|
||||||
*/
|
*/
|
||||||
public void deleteNode(EntryNode entryNode) {
|
public void deleteNode(EntryNode entryNode) {
|
||||||
@ -112,6 +112,7 @@ public class LeeCode146 {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 在尾部增加某个节点
|
* 在尾部增加某个节点
|
||||||
|
*
|
||||||
* @param node
|
* @param node
|
||||||
*/
|
*/
|
||||||
public void addNode(EntryNode node) {
|
public void addNode(EntryNode node) {
|
||||||
|
Loading…
Reference in New Issue
Block a user