Golang | Leetcode Golang题解之第460题LFU缓存

题目:

题解:

import "container/heap"
type LFUCache struct {
    h  *NodeHeap
    nodemap map[int]*Node
    size, cap int
    opcnt int
}

type Node struct {
	freq, lastop int
	key, value   int
	index        int
}
type NodeHeap []*Node
func (h NodeHeap) Len() int { return len(h) }
func (h NodeHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
	h[i].index, h[j].index = h[j].index, h[i].index
}
func (h NodeHeap) Less(i, j int) bool {
	if h[i].freq < h[j].freq {
		return true
	} else if h[i].freq > h[j].freq {
		return false
	} else {
		return h[i].lastop < h[j].lastop
	}
}
func (h *NodeHeap) Push(x interface{}) {
	*h = append(*h, x.(*Node))
}
func (h *NodeHeap) Pop() interface{} {
	ret := (*h)[len(*h)-1]
	*h = (*h)[:len(*h)-1]
	return ret
}

func Constructor(capacity int) LFUCache {
    cache := LFUCache{&NodeHeap{}, map[int]*Node{}, 0, capacity, 0}
    heap.Init(cache.h)
    return cache
}


func (this *LFUCache) Get(key int) int {
    if this.cap == 0 {
        return -1
    }
    node, ok := this.nodemap[key]
    if !ok {
        return -1
    } else {
        ret := node.value
        node.freq++
        node.lastop = this.opcnt
        this.opcnt++
        heap.Fix(this.h, node.index)
        return ret
    }
}


func (this *LFUCache) Put(key int, value int) {
    if this.cap == 0 {
        return
    }
    node, ok := this.nodemap[key]
    if ok {
        node.freq++
        node.lastop = this.opcnt
        this.opcnt++
        node.value = value
        heap.Fix(this.h, node.index)
    } else {
        if this.size == this.cap {
            kicked := heap.Pop(this.h)
            delete(this.nodemap, kicked.(*Node).key)
        } else {
            this.size++
        }
        newnode := &Node{1, this.opcnt, key, value, this.h.Len()}
        this.opcnt++
        heap.Push(this.h, newnode)
        this.nodemap[key] = newnode
    }
}  


/**
 * Your LFUCache object will be instantiated and called as such:
 * obj := Constructor(capacity);
 * param_1 := obj.Get(key);
 * obj.Put(key,value);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值