@@ -346,4 +346,34 @@ class LRUCache {
346346<img src="../pictures/qrcode.jpg" width=200 >
347347</p>
348348
349- ======其他语言代码======
349+ ======其他语言代码======
350+ ```python3
351+ """
352+ 所谓LRU缓存,根本的难点在于记录最久被使用的键值对,这就设计到排序的问题,
353+ 在python中,天生具备排序功能的字典就是OrderDict。
354+ 注意到,记录最久未被使用的键值对的充要条件是将每一次put/get的键值对都定义为
355+ 最近访问,那么最久未被使用的键值对自然就会排到最后。
356+ 如果你深入python OrderDict的底层实现,就会知道它的本质是个双向链表+字典。
357+ 它内置支持了
358+ 1. move_to_end来重排链表顺序,它可以让我们将最近访问的键值对放到最后面
359+ 2. popitem来弹出键值对,它既可以弹出最近的,也可以弹出最远的,弹出最远的就是我们要的操作。
360+ """
361+ from collections import OrderedDict
362+ class LRUCache:
363+ def __init__ (self , capacity : int ):
364+ self.capacity = capacity # cache的容量
365+ self.visited = OrderedDict () # python内置的OrderDict具备排序的功能
366+ def get (self , key : int ) -> int:
367+ if key not in self.visited:
368+ return -1
369+ self.visited.move_to_end (key ) # 最近访问的放到链表最后,维护好顺序
370+ return self.visited[key]
371+ def put (self , key : int , value : int ) -> None:
372+ if key not in self.visited and len (self .visited ) == self.capacity:
373+ # last=False时,按照FIFO顺序弹出键值对
374+ # 因为我们将最近访问的放到最后,所以最远访问的就是最前的,也就是最first的,故要用FIFO顺序
375+ self.visited.popitem (last =False )
376+ self.visited[key]=value
377+ self.visited.move_to_end (key ) # 最近访问的放到链表最后,维护好顺序
378+
379+ ```
0 commit comments