LRU
2020-07-28 本文已影响0人
dalewong
LRU: 缓存置换算法,mysql page, redis缓存等使用
实现一个LRU, 主要需要考虑几点:
一个双向链表,一个hash map
未命名.jpg
#
# @lc app=leetcode.cn id=146 lang=python
#
# [146] LRU缓存机制
#
# @lc code=start
class DLink(object):
def __init__(self, key=None, value=None, prev=None, next=None):
self.key = key
self.value = value
self.prev = prev
self.next = next
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.head = DLink()
self.tail = DLink()
self.head.prev = self.tail
self.tail.next = self.head
self.page_cache = {}
self.current_volumn = 0
def get(self, key):
"""
:type key: int
:rtype: int
"""
result = self.page_cache.get(key)
if result:
self.add_head(self.result)
return result.value
else:
return -1
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: None
"""
node = self.page_cache.get(key)
if node:
# 这里需要注意有node的时候,需要把node前置
node.value = value
self.remove_node(node)
self.add_head(node)
return
if self.current_volumn < self.capacity:
node = DLink(key, value, self.tail)
self.add_tail(node)
self.current_volumn += 1
self.page_cache[key] = node
else:
node = DLink(key, value, None, self.head)
self.add_head(node)
t = self.remove_tail()
self.page_cache.pop(t.key)
self.page_cache[key] = value
def remove_node(node):
node.prev.next = node.next
node.next.prev = node.prev
def add_head(node):
node.prev = self.head
node.next = self.head.next
self.head.next = node
self.head.next.prev = node
def add_tail(node):
self.remove_node(node)
self.add_head(node)
def remove_tail():
node = self.tail.prev
self.remove_node(node)
return node