LRU Cache
来源:互联网 发布:新网域名证书生成 编辑:程序博客网 时间:2024/04/30 04:44
Q:
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.
Solution:
Both set and get are counted as a operation, use a doubly linked list to track the head and the tail. The get and set have O(1) time.
class DoublyLinkedListNode { DoublyLinkedListNode prev; DoublyLinkedListNode next; int key; int val; public DoublyLinkedListNode(int key, int val) { this.key = key; this.val = val; prev = null; next = null; }} public class LRUCache { HashMap<Integer, DoublyLinkedListNode> cache = new HashMap<Integer, DoublyLinkedListNode>(); // head.prev points to the tail of the list, so that we can get the tail in O(1) time. DoublyLinkedListNode head = null; private int capacity; private void removeNode(DoublyLinkedListNode node) { if (node == head) head = node.next; node.prev.next = node.next; node.next.prev = node.prev; } private void addHead(DoublyLinkedListNode node) { if (head == null) { head = node; head.prev = head; head.next = head; } else { node.next = head; node.prev = head.prev; head.prev.next = node; head.prev = node; head = node; } } public LRUCache(int capacity) { this.capacity = capacity; } public int get(int key) { if (!cache.containsKey(key)) return -1; DoublyLinkedListNode node = cache.get(key); removeNode(node); addHead(node); return node.val; } public void set(int key, int value) { if (cache.containsKey(key)) { DoublyLinkedListNode node = cache.get(key); node.val = value; cache.put(key, node); removeNode(node); addHead(node); } else { if (cache.size() < capacity) { DoublyLinkedListNode node = new DoublyLinkedListNode(key, value); cache.put(key, node); addHead(node); } else { DoublyLinkedListNode tail = head.prev; removeNode(tail); cache.remove(tail.key); DoublyLinkedListNode newHead = new DoublyLinkedListNode(key, value); cache.put(key, newHead); addHead(newHead); } } }}
0 0
- LRU Cache
- LRU Cache
- LRU Cache
- LRU Cache
- LRU Cache
- lru cache
- LRU Cache
- LRU Cache
- LRU Cache
- LRU Cache
- LRU Cache
- LRU Cache
- LRU Cache
- LRU cache
- LRU Cache
- LRU Cache
- LRU Cache
- LRU Cache
- 组件重写小例子-- Vgroup 变为从下到上排列
- 五步教你实现使用Nginx+uWSGI+Django方法部署Django程序
- 全国省市县数据库
- 研究一下netty4
- 防止单例在反序列化后成多例
- LRU Cache
- 创建sitemap的步骤
- 差网络环境模拟工具 Clumsy
- 多线程内存泄露
- Bundle MVC4解决方法集合
- PCRE使用
- VC++ DirectShow的使用
- Random number for GPU
- 最简单注册apple id方法,无需苹果设备,无需VISA等信用卡