File tree Expand file tree Collapse file tree 1 file changed +14
-11
lines changed Expand file tree Collapse file tree 1 file changed +14
-11
lines changed Original file line number Diff line number Diff line change 1- # Approach 1 - Ordered Dictionary
1+ # Approach 2: Built-in
22
3- # Time: O(1)
3+ # Time: O(1), for both get and put
44# Space: O(capacity)
55
66from collections import OrderedDict
77
8- class LRUCache ( OrderedDict ) :
8+ class LRUCache :
99
1010 def __init__ (self , capacity : int ):
1111 self .capacity = capacity
12+ self .dic = OrderedDict ()
1213
1314
1415 def get (self , key : int ) -> int :
15- if key not in self :
16+ if key not in self . dic :
1617 return - 1
17- self .move_to_end (key )
18- return self [key ]
18+
19+ self .dic .move_to_end (key )
20+ return self .dic [key ]
1921
2022
2123 def put (self , key : int , value : int ) -> None :
22- if key in self :
23- self .move_to_end (key )
24- self [key ] = value
25- if len (self ) > self .capacity :
26- self .popitem (last = False )
24+ if key in self .dic :
25+ self .dic .move_to_end (key )
26+
27+ self .dic [key ] = value
28+ if len (self .dic ) > self .capacity :
29+ self .dic .popitem (last = False )
2730
2831
2932
You can’t perform that action at this time.
0 commit comments