[LeetCode]题解(python):146-LRU Cache

本文详细介绍了如何实现LRU缓存算法,并提供了相应的Python代码实现。通过使用OrderedDict数据结构,有效地实现了缓存的最近最少使用策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目来源:

  https://leetcode.com/problems/lru-cache/


实现一个LRU缓存。直接上代码。


代码(python):

 1 class LRUCache(object):
 2 
 3     def __init__(self, capacity):
 4         """
 5         :type capacity: int
 6         """
 7         LRUCache.capacity = capacity
 8         LRUCache.length = 0
 9         LRUCache.dict = collections.OrderedDict()
10 
11     def get(self, key):
12         """
13         :rtype: int
14         """
15         try:
16             value = LRUCache.dict[key]
17             del LRUCache.dict[key]
18             LRUCache.dict[key] = value
19             return value
20         except:
21             return -1
22 
23     def set(self, key, value):
24         """
25         :type key: int
26         :type value: int
27         :rtype: nothing
28         """
29         try:
30             del LRUCache.dict[key]
31             LRUCache.dict[key] = value
32         except:
33             if LRUCache.length == LRUCache.capacity:
34                 LRUCache.dict.popitem(last = False)
35                 LRUCache.length -= 1
36             LRUCache.dict[key] = value
37             LRUCache.length += 1
38         
View Code

 

转载于:https://www.cnblogs.com/chruny/p/5477982.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值