type LFUCache struct {
head, tail *Node
m map[int]*Node
size, capacity int
}
type Node struct {
key, value, count int
pre, next *Node
}
func Constructor(capacity int) LFUCache {
cache := LFUCache{
head: new(Node),
tail: new(Node),
m: map[int]*Node{},
capacity: capacity,
}
cache.head.next = cache.tail
cache.tail.pre = cache.head
return cache
}
func (this *LFUCache) Get(key int) int {
if this.capacity == 0 {
return -1
}
if node, ok := this.m[key]; !ok {
return -1
} else {
node.count++
this.m[key] = node
this.Sort(node, true)
return node.value
}
}
func (this *LFUCache) Sort(node *Node, b bool) {
if b {
this.Remove(node)
}
t := this.head.next
for t != this.tail && t.count > node.count {
t = t.next
}
this.AddFont(t, node)
}
func (this *LFUCache) Put(key int, value int) {
if this.capacity == 0 {
return
}
node, ok := this.m[key]
if !ok {
if this.size == this.capacity {
this.RemoveTail()
this.size--
}
new := &Node{
key: key,
value: value,
count: 1,
}
this.size++
node = new
this.Sort(new, false)
} else {
node.value = value
node.count++
this.Sort(node, true)
}
this.m[key] = node
}
func (this *LFUCache) AddFont(font *Node, new *Node) {
new.next = font
new.pre = font.pre
font.pre.next = new
font.pre = new
}
func (this *LFUCache) RemoveTail() *Node {
node := this.tail.pre
this.Remove(node)
delete(this.m, node.key)
return node
}
func (this *LFUCache) Remove(node *Node) {
node.pre.next = node.next
node.next.pre = node.pre
}
Go LFU缓存(链表实现)
最新推荐文章于 2024-09-17 18:12:41 发布