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

题目来源:

  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