lRUCache.put(2, 2); // 缓存是 {1=1, 2=2} lRUCache.get(1); // 返回 1 lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3} lRUCache.get(2); // 返回 -1 (未找到) lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3} lRUCache...
java中可以使用LinkeHashMap来实现LRU缓存。 程序: C++ class LRUCache { public: LRUCache(int capacity) { cap = capacity; } int get(int key) { auto it = map.find(key); if(it == map.end()) return -1; l.splice(l.begin(), l, it->second); return it->second->second; } void pu...
lRUCache.put(1, 1); // 缓存是 {1=1} lRUCache.put(2, 2); // 缓存是 {1=1, 2=2} lRUCache.get(1); // 返回 1 lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3} lRUCache.get(2); // 返回 -1 (未找到) lRUCache.put(4, 4); // 该操作会使得关...
int capacity = 2; LRUCache lRUCache = new LRUCache(capacity); lRUCache.put(1, 1); // 缓存是 {1=1} lRUCache.put(2, 2); // 缓存是 {1=1, 2=2} System.out.println(lRUCache); lRUCache.get(1); // 返回 1 lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1...
146. LRU缓存机制 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
importjava.util.LinkedHashMap;importjava.util.Map;publicclassLeetCode_146 {publicstaticvoidmain(String[] args) {// 测试用例LRUCachelRUCache=newLRUCache(2);lRUCache.put(1, 1); // 缓存是 {1=1}lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}lRUCache.get(1); // 返回 1lRUCache.put...
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。 写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上...
最近在学操作系统,正好用这个复习一些LRU缓存机制,也就是最近最少使用(least recently used)。 在java和python中有已经封装好的数据结构可以使用,不过本题肯定也不是为了使用那些封装好的数据结构。因此我们需要自己手动实现。 需要一个哈希表和一个双向链表,同时题目要求put和get操作的时间复杂度为O(1),所以也不能...
public Node next; public Integer value; private Node(Integer key, Node parent, Node next, Integer value) { this.key = key; this.parent = parent; this.next = next; this.value = value; } } public LRUCache(int capacity) { this.capacity = capacity; ...
class LRUCache {private:list<pair<int,int>>cache;unordered_map<int,list<pair<int,int>>::iterator>key2node;int cap;//cache的最大容量public:LRUCache(int capacity):cap(capacity){}int get(int key) {//获取键key所对应的val值if(key2node.find(key)==key2node.end())return -1;//如果存在...