/
LRUCache.py
35 lines (32 loc) · 926 Bytes
/
LRUCache.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
from collections import OrderedDict
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.dictionary = OrderedDict()
self.capacity = capacity
def get(self, key):
"""
:rtype: int
"""
if key in self.dictionary:
temp = self.dictionary.pop(key)
self.dictionary[key] = temp
return temp
else: return -1
def set(self, key, value):
"""
:type key: int
:type value: int
:rtype: nothing
"""
if key in self.dictionary:
self.dictionary.pop(key)()
self.dictionary[key] = value
else:
if len(self.dictionary) >= self.capacity:
self.dictionary.popitem(last=False)
self.dictionary[key] = value
else:
self.dictionary[key] = value