Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
模拟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)

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理