17-146. LRU Cache

题目描述:

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

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 if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

The cache is initialized with a positive capacity.

Follow up:
Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4

代码:

 1 class LRUCache(object):
 2 
 3     def __init__(self, capacity):
 4         """
 5         :type capacity: int
 6         """
 7         self.dic = collections.OrderedDict()
 8         self.remain = capacity
 9 
10     def get(self, key):
11         """
12         :type key: int
13         :rtype: int
14         """
15         if key not in self.dic:
16             return -1
17         v = self.dic.pop(key) 
18         self.dic[key] = v   # set key as the newest one
19         return v
20 
21     def put(self, key, value):
22         """
23         :type key: int
24         :type value: int
25         :rtype: None
26         """
27         if key in self.dic:    
28             self.dic.pop(key)
29         else:
30             if self.remain > 0:
31                 self.remain -= 1  
32             else:  # self.dic is full
33                 self.dic.popitem(last=False) 
34         self.dic[key] = value
35 
36 
37 # Your LRUCache object will be instantiated and called as such:
38 # obj = LRUCache(capacity)
39 # param_1 = obj.get(key)
40 # obj.put(key,value)
原文地址:https://www.cnblogs.com/tbgatgb/p/10989693.html