题解 | #设计LRU缓存结构#
设计LRU缓存结构
https://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84
package main
type DLinkedNode struct {
key, value int
prev, next *DLinkedNode
}
type Solution struct {
cache map[int]*DLinkedNode
capacity int
head, tail *DLinkedNode
}
func initDLinkedNode(key, value int) *DLinkedNode {
return &DLinkedNode{
key: key,
value: value,
}
}
func Constructor(capacity int) Solution {
lru := Solution{
cache: map[int]*DLinkedNode{},
head: initDLinkedNode(0, 0),
tail: initDLinkedNode(0, 0),
capacity: capacity,
}
lru.head.next = lru.tail
lru.tail.prev = lru.head
return lru
}
func (this *Solution) get(key int) int {
if node, ok := this.cache[key]; ok {
this.moveToHead(node)
return node.value
}
return -1
}
func (this *Solution) set(key int, value int) {
if node, ok := this.cache[key]; ok {
node.value = value
this.moveToHead(node)
} else {
newNode := initDLinkedNode(key, value)
this.cache[key] = newNode
this.addToHead(newNode)
if len(this.cache) > this.capacity {
removed := this.removeTail()
delete(this.cache, removed.key)
}
}
}
func (this *Solution) addToHead(node *DLinkedNode) {
node.prev = this.head
node.next = this.head.next
this.head.next.prev = node
this.head.next = node
}
func (this *Solution) removeNode(node *DLinkedNode) {
node.prev.next = node.next
node.next.prev = node.prev
}
func (this *Solution) moveToHead(node *DLinkedNode) {
this.removeNode(node)
this.addToHead(node)
}
func (this *Solution) removeTail() *DLinkedNode {
node := this.tail.prev
this.removeNode(node)
return node
}

查看12道真题和解析