有什么做兼职的网站比较好,网站开源模板,公司查询系统官网,新会新闻官网go语言实现LRU Cache 题目描述详细代码 题目描述
设计和构建一个“最近最少使用”缓存#xff0c;该缓存会删除最近最少使用的项目。缓存应该从键映射到值(允许你插入和检索特定键对应的值)#xff0c;并在初始化时指定最大容量。当缓存被填满时#xff0c;它应该删除最近最… go语言实现LRU Cache 题目描述详细代码 题目描述
设计和构建一个“最近最少使用”缓存该缓存会删除最近最少使用的项目。缓存应该从键映射到值(允许你插入和检索特定键对应的值)并在初始化时指定最大容量。当缓存被填满时它应该删除最近最少使用的项目。
它应该支持以下操作 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果密钥 (key) 存在于缓存中则获取密钥的值总是正数否则返回 -1。 写入数据 put(key, value) - 如果密钥不存在则写入其数据值。当缓存容量达到上限时它应该在写入新数据之前删除最近最少使用的数据值从而为新的数据值留出空间。
详细代码
type LRUCache struct {capacity intm map[int]*Nodehead, tail *Node
}type Node struct {Key intValue intPre, Next *Node
}func Constructor(capacity int) LRUCache {head, tail : Node{}, Node{}head.Next tailtail.Pre headreturn LRUCache{capacity: capacity,m: map[int]*Node{},head: head,tail: tail,}
}func (this *LRUCache) Get(key int) int {// 存在放到头if v, ok : this.m[key]; ok {this.moveToHead(v)return v.Value}// 不存在返回-1return -1
}func (this *LRUCache) Put(key int, value int) {// 已经存在了if v, ok : this.m[key];ok{v.Value valuethis.moveToHead(v)return }if this.capacitylen(this.m){rmKey : this.removeTail()delete(this.m ,rmKey)}newNode : Node{Key: key, Value: value}this.m[key] newNodethis.addToHead(newNode)
}func (this *LRUCache) moveToHead(node *Node) {this.deleteNode(node)this.addToHead(node)
}func (this *LRUCache) deleteNode(node *Node) {node.Pre.Next node.Nextnode.Next.Pre node.Pre
}func (this *LRUCache) addToHead(node *Node) {// 先让node位于现存第一位元素之前this.head.Next.Pre node// 通过node的next指针让原始第一位元素放到第二位node.Next this.head.Next// 捆绑node和head的关系this.head.Next nodenode.Pre this.head
}func (this *LRUCache)removeTail()int{node : this.tail.Prethis.deleteNode(node)return node.Key
}/*** Your LRUCache object will be instantiated and called as such:* obj : Constructor(capacity);* param_1 : obj.Get(key);* obj.Put(key,value);*/