4 Star 7 Fork 4

ShirDon-廖显东/零基础Go语言算法实战源码

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
interview4-8.go 1.76 KB
一键复制 编辑 原始数据 按行查看 历史
ShirDon-廖显东 提交于 2024-04-22 14:56 . first commit
// ++++++++++++++++++++++++++++++++++++++++
// 《零基础Go语言算法实战》源码
// ++++++++++++++++++++++++++++++++++++++++
// Author:廖显东(ShirDon)
// Blog:https://www.shirdon.com/
// Gitee:https://gitee.com/shirdonl/goAlgorithms.git
// Buy link :https://item.jd.com/14101229.html
// ++++++++++++++++++++++++++++++++++++++++
package main
import "fmt"
type LRUCache struct {
capacity int
head, tail *Node
values map[int]*Node
}
type Node struct {
key, value int
prev, next *Node
}
func Constructor(capacity int) LRUCache {
return LRUCache{
values: map[int]*Node{},
capacity: capacity,
}
}
func (lr *LRUCache) Get(key int) int {
node, ok := lr.values[key]
if !ok {
return -1
}
lr.moveToLast(node)
return node.value
}
func (lr *LRUCache) moveToLast(node *Node) {
if node == lr.tail {
return
}
if node == lr.head {
lr.head = lr.head.next
lr.head.prev = nil
} else {
node.prev.next = node.next
node.next.prev = node.prev
}
lr.tail.next = node
node.prev = lr.tail
lr.tail = lr.tail.next
lr.tail.next = nil
}
func (lr *LRUCache) Put(key int, value int) {
if _, ok := lr.values[key]; ok {
lr.values[key].value = value
lr.moveToLast(lr.values[key])
return
}
if len(lr.values) < lr.capacity {
lr.append(key, value)
return
}
node := lr.head
lr.moveToLast(node)
delete(lr.values, node.key)
lr.values[key] = node
node.key = key
node.value = value
}
func (lr *LRUCache) append(key, value int) {
node := &Node{
key: key,
value: value,
}
if lr.tail == nil {
lr.tail = node
lr.head = node
} else {
lr.tail.next = node
node.prev = lr.tail
lr.tail = node
}
lr.values[key] = node
}
func main() {
obj := Constructor(2)
obj.Put(5, 88)
res := obj.Get(5)
fmt.Println(res)
}
//$ go run interview3-7.go
//88
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/shirdonl/goAlgorithms.git
git@gitee.com:shirdonl/goAlgorithms.git
shirdonl
goAlgorithms
零基础Go语言算法实战源码
3e77a12194dd

搜索帮助