File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ # Learning how to use OrderedDict() and its popitem(last=False) function to pop the first in element
2+
3+
4+ class LRUCache :
5+
6+ def __init__ (self , capacity : int ):
7+ self .capacity = capacity
8+ self .dict = collections .OrderedDict ()
9+
10+
11+ def get (self , key : int ) -> int :
12+ if key in self .dict :
13+ v = self .dict [key ]
14+ del self .dict [key ]
15+ self .dict [key ] = v
16+ return self .dict [key ]
17+ else :
18+ return - 1
19+
20+ def put (self , key : int , value : int ) -> None :
21+ if key in self .dict :
22+ del self .dict [key ]
23+ self .dict [key ] = value
24+
25+ else :
26+ if len (self .dict ) >= self .capacity :
27+ self .dict .popitem (last = False )
28+ self .dict [key ] = value
29+
30+
31+ # Your LRUCache object will be instantiated and called as such:
32+ # obj = LRUCache(capacity)
33+ # param_1 = obj.get(key)
34+ # obj.put(key,value)
You can’t perform that action at this time.
0 commit comments