146. LRU缓存机制
难度: 中等
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 type LRUCache struct { head,tail *Node Keys map [int ]*Node Cap int } type Node struct { Key,Val int Prev,Next *Node } func Constructor (capacity int ) LRUCache { return LRUCache{Keys:make (map [int ]*Node),Cap:capacity} } func (this *LRUCache) Get(key int ) int { if node, ok := this.Keys[key]; ok { this.Remove(node) this.Add(node) return node.Val } return -1 } func (this *LRUCache) Put(key int , value int ) { if node, ok := this.Keys[key]; ok { node.Val = value this.Remove(node) this.Add(node) return } else { node = &Node{Key: key, Val: value} this.Keys[key] = node this.Add(node) } if len (this.Keys) > this.Cap { delete (this.Keys, this.tail.Key) this.Remove(this.tail) } } func (this *LRUCache) Add(node *Node) { node.Prev = nil node.Next = this.head if this.head != nil { this.head.Prev = node } this.head = node if this.tail == nil { this.tail = node this.tail.Next = nil } } func (this *LRUCache) Remove(node *Node) { if node == this.head { this.head = node.Next node.Next = nil return } if node == this.tail { this.tail = node.Prev node.Prev.Next = nil node.Prev = nil return } node.Prev.Next = node.Next node.Next.Prev = node.Prev }
LRU算法浅析
go实现LRU cache
原文链接: https://dashen.tech/2015/03/01/leetcode-146-LRU缓存机制/
版权声明: 转载请注明出处.