Go LFU缓存(链表实现)

460. LFU 缓存

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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值