-
Notifications
You must be signed in to change notification settings - Fork 481
/
0146.py
35 lines (30 loc) · 809 Bytes
/
0146.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import collections
class LRUCache:
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.cache = collections.OrderedDict()
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key in self.cache:
value = self.cache.pop(key)
self.cache[key] = value
return value
return -1
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
if key in self.cache:
self.cache.pop(key)
else:
if len(self.cache) == self.capacity:
self.cache.popitem(last=False)
self.cache[key] = value