描述
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。
进阶:
你是否可以在 O(1) 时间复杂度内完成这两种操作?
示例:
LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 该操作会使得密钥 2 作废
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得密钥 1 作废
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4
思路
利用双向链表和map实现 map存储key对应的双向链表中的节点 双向链表用来实现LRU
1. get操作 需要将map 中key对应的节点移动到头部位置
2. put操作 如果key存在 更新value 并将map 中key对应的节点移动到头部位置 ,不存在的话需要判断是否超出容量 如果超出, 则删除尾部节点并
将新节点插到头部位置,没有超出 则直接插到头部位置
实现
type LRUCache struct {
Head *LRUCacheNode
Last *LRUCacheNode
Cap int
Map map[int]*LRUCacheNode
}
type LRUCacheNode struct {
Key int
Value int
Pre *LRUCacheNode
Next *LRUCacheNode
}
func Constructor(capacity int) LRUCache {
cache := LRUCache{}
cache.Cap = capacity
cache.Map = make(map[int]*LRUCacheNode)
return cache
}
func (this *LRUCache) Get(key int) int {
if node, ok := this.Map[key]; ok {
if node == this.Last && node != this.Head {
this.Last = node.Pre
}
this.Head = DoubleLinkMoveToHead(node, this.Head)
return node.Value
} else {
return -1
}
}
func (this *LRUCache) Put(key int, value int) {
if node, ok := this.Map[key]; ok {
node.Value = value
if node == this.Last && node != this.Head {
this.Last = node.Pre
}
this.Head = DoubleLinkMoveToHead(node, this.Head)
return
} else if len(this.Map) >= this.Cap {
lastKey := this.Last.Key
last := this.Map[lastKey]
this.Last = last.Pre
DoubleLinkDelete(last)
delete(this.Map, lastKey)
}
this.Head = DoubleLinkInsert(this.Head, key, value)
this.Map[key] = this.Head
if len(this.Map) == 1 {
this.Last = this.Head
}
return
}
func DoubleLinkInsert(head *LRUCacheNode, key, value int) *LRUCacheNode {
newNode := new(LRUCacheNode)
newNode.Key = key
newNode.Value = value
if head == nil {
return newNode
} else {
newNode.Next = head
head.Pre = newNode
return newNode
}
}
func DoubleLinkDelete(node *LRUCacheNode) {
pre := node.Pre
next := node.Next
if pre != nil {
pre.Next = next
}
if next != nil {
next.Pre = pre
}
node = nil
}
func DoubleLinkMoveToHead(node *LRUCacheNode, head *LRUCacheNode) *LRUCacheNode {
if node != head {
DoubleLinkDelete(node)
node.Next = head
node.Pre = nil
head.Pre = node
return node
}
return head
}