LRU Cache
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(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.
import java.util.HashMap; public class LRUCache { private class CacheObject { public CacheObject pre; public CacheObject next; public int key; public int value; public CacheObject(int key,int value) { this.key = key; this.value = value; this.next = null; this.pre = null; } } public HashMap table = new HashMap (); public CacheObject head; public CacheObject tail; public int capacity; private boolean isTail(CacheObject co){ if (tail==null) { return false; } return tail==co; } private void fixTail(CacheObject co) { if (tail==head){ return; } if (isTail(co)){ tail = co.pre; tail.next = null; } } private void move2head(CacheObject co){ if (head==co){ return; } if (tail==head){ CacheObject oldHead = head; head = co; head.next = oldHead; head.pre = null; oldHead.pre = co; oldHead.next = null; return; } if (head != null){ CacheObject pre = co.pre; CacheObject next = co.next; if (pre!=null && next !=null){ pre.next = next; next.pre = pre; } head.pre = co; co.next = head; co.pre = null; } head = co; } public LRUCache(int capacity) { this.capacity = capacity; } public int get(int key) { if (table.containsKey(key)) { CacheObject added = (CacheObject)table.get(key); if (head!=added){ fixTail(added); move2head(added); } return added.value; } return -1; } public void set(int key, int value) { if (table.containsKey(key)){ CacheObject tmp = (CacheObject) table.get(key); fixTail(tmp); move2head(tmp); tmp.value = value; return; } CacheObject added = new CacheObject(key, value); if (this.capacity == table.size()) { table.remove(tail.key); fixTail(tail); } if (table.size()==0) { tail = added; head = added; } else { move2head(added); } table.put(key,added); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步