1
+ class Node :
2
+ def __init__ (self ,key ,val ):
3
+ self .key = key
4
+ self .val = val
5
+ self .next = None
6
+ self .prev = None
7
+
8
+ class LRUCache :
9
+ """
10
+ 146. LRU 缓存机制
11
+ https://leetcode-cn.com/problems/lru-cache
12
+ 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。
13
+ 实现 LRUCache 类:
14
+ 1. LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
15
+ 2. int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
16
+ 3. void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
17
+ """
18
+ def __init__ (self , capacity : int ):
19
+ self .dict = {}
20
+ self .head = Node (None , None )
21
+ self .tail = Node (None , None )
22
+ self .head .next = self .tail
23
+ self .tail .prev = self .head
24
+ self .capacity = capacity
25
+
26
+ def insert (self , node ):
27
+ # 前置
28
+ node .next = self .head .next
29
+ node .prev = self .head
30
+
31
+ self .head .next .prev = node
32
+ self .head .next = node
33
+
34
+
35
+ def delete (self , node ):
36
+ node .prev .next , node .next .prev = node .next , node .prev
37
+
38
+ def get (self , key : int ) -> int :
39
+ if key not in self .dict :
40
+ return - 1
41
+ node = self .dict [key ]
42
+ self .delete (node )
43
+ self .insert (node )
44
+ return node .val
45
+
46
+ def put (self , key : int , value : int ) -> None :
47
+ if key in self .dict :
48
+ node = self .dict [key ]
49
+ node .val = value
50
+ self .delete (node )
51
+ self .insert (node )
52
+ return
53
+
54
+ if len (self .dict ) == self .capacity :
55
+ node = self .tail .prev
56
+ self .delete (node )
57
+ del self .dict [node .key ]
58
+
59
+ node = Node (key , value )
60
+ self .dict [key ] = node
61
+ self .insert (node )
62
+
63
+
64
+ # Your LRUCache object will be instantiated and called as such:
65
+ # obj = LRUCache(capacity)
66
+ # param_1 = obj.get(key)
67
+ # obj.put(key,value)
0 commit comments