cache.put(1, 1); // 缓存是 {1=1} cache.put(2, 2); // 缓存是 {1=1, 2=2} cache.get(1); // 返回 1,缓存更新为 {2=2, 1=1} cache.put(3, 3); // 淘汰最久未使用的 key 2,缓存变成 {1=1, 3=3} cache.get(2); // 返回 -1(未找到) 三、误区:直接用数组/
Python3 Javaclass LRUCache(collections.OrderedDict): def __init__(self, capacity: int): super().__init__() self.capacity = capacity def get(self, key: int) -> int: if key not in self: return -1 self.move_to_end(key) ...
Design and implement a data structure forLeast Recently Used (LRU) cache. It should support the following operations:getandput. get(key)- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value)- Set or insert the value ...
HashData Java 链表 0 1.1K 0 IsayamaTMnoheart ・ 2021.05.24 c++: LRU Cache [该用户太懒了,只写了 117 行代码] 双向链表 C++ 哈希表 设计 2 1.2K 0 handsomechar ・ 2021.05.22 labuladong 解题思路部分参考https://labuladong.gitbook.io/algo/mu-lu-ye-1/mu-lu-ye-2/lru-suan-fa 代码 C+...
lRUCache.get(2); // 返回 -1 (未找到) lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3} lRUCache.get(1); // 返回 -1 (未找到) lRUCache.get(3); // 返回 3 lRUCache.get(4); // 返回 4 来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/lru...
【Leetcode】 LRU Cache https://leetcode.com/problems/lru-cache/题目: getandset.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) 思路: 用链表存储key的顺序关系,不管是用栈还是队列,在get元素和set已有元素...
import java.util.Map; /** * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/lru-cache */ public class LRUCache { class Node { private int key; private int value; private Node pre; private Node next; Node(int key, int value) { ...
题目信息链接: https://leetcode-cn.com/problems/lru-cache/题目描述: 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。获取数据 …
Java好,Java妙,Java的ADC真奇妙(ADC=LinkedHashMap) class LRUCache { int capacity; LinkedHashMap<Integer, Integer> cache; public LRUCache(int capacity) { this.capacity = capacity; cache = new LinkedHashMap<Integer, Integer>(capacity, 0.75f, true) { ...
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...