LeetCode 146. LRU Cache

前言

听说某条很喜欢出这道题
一道老题目了,思路就是双向链表 + hashMap

代码实现

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
self.pre = None

class LRUCache(object):

def __init__(self, capacity):
"""
:type capacity: int
"""
self.cap = capacity
self.head = None
self.tail = None
self.cache = {}
self.node_map = {}
self.size = 0


def get(self, key):
"""
:type key: int
:rtype: int
"""
if self.cap == 0:
return -1
if key in self.cache:
node = self.node_map[key]
self.put_head(node)
return self.cache[key] if key in self.cache else -1

def put_head(self, node):
if node.val in self.node_map:
if self.head.val == node.val:
return
node.pre.next = node.next
node.next.pre = node.pre
if self.tail.val == node.val:
self.tail = node.pre
node.next = self.head
node.pre = self.tail
self.head.pre = node
self.tail.next = node
self.head = node


def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
if self.cap == 0:
return
if key not in self.cache:
if self.size == self.cap:
tail = self.tail
del self.cache[tail.val]
tail.pre.next = tail.next
tail.next.pre = tail.pre
self.tail = tail.pre
del self.node_map[tail.val]
else:
self.size += 1
node = None
if key in self.node_map:
node = self.node_map[key]
else:
node = Node(key)
self.cache[key] = value
if self.head == None:
self.head = node
self.tail = node
node.next = node
node.pre = node
else:
self.put_head(node)
self.node_map[key] = node