Posted on 2023-07-18 17:47
Uriel 阅读(31)
评论(0) 编辑 收藏 引用 所属分类:
模拟 、
闲来无事重切Leet Code
模拟LRU Cache,用python的
OrderedDict极度适合!
1 #146
2 #Runtime: 990 ms (Beats 30.89%)
3 #Memory: 78.8 MB (Beats 74.63%)
4
5 class LRUCache(object):
6
7 def __init__(self, capacity):
8 """
9 :type capacity: int
10 """
11 self.cap = capacity
12 self.cache = OrderedDict()
13
14
15 def get(self, key):
16 """
17 :type key: int
18 :rtype: int
19 """
20 if key not in self.cache:
21 return -1
22 v = self.cache.pop(key)
23 self.cache[key] = v
24 return v
25
26
27 def put(self, key, value):
28 """
29 :type key: int
30 :type value: int
31 :rtype: None
32 """
33 if key in self.cache:
34 self.cache.pop(key)
35 elif len(self.cache) == self.cap:
36 self.cache.popitem(last=False)
37 self.cache[key] = value
38
39
40
41 # Your LRUCache object will be instantiated and called as such:
42 # obj = LRUCache(capacity)
43 # param_1 = obj.get(key)
44 # obj.put(key,value)