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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
|
type Node struct { Key, Value int Next, Prev *Node }
type LinkedList struct { Head, Tail *Node Len int }
func NewList() LinkedList { head := new(Node) tail := new(Node) head.Next = tail tail.Prev = head return LinkedList{head, tail, 0} }
func (list *LinkedList) AddLast(x *Node) { x.Prev = list.Tail.Prev x.Next = list.Tail
list.Tail.Prev.Next = x list.Tail.Prev = x
list.Len++ }
func (list *LinkedList) Remove(x *Node) { x.Prev.Next = x.Next x.Next.Prev = x.Prev
list.Len-- }
func (list *LinkedList) RemoveFirst() *Node { if list.Head.Next == list.Tail { return nil } first := list.Head.Next list.Remove(first) return first }
type LRUCache struct { m map[int]*Node cache LinkedList cap int }
func (this *LRUCache) makeRecently(key int) { x := this.m[key] this.cache.Remove(x) this.cache.AddLast(x) }
func (this *LRUCache) addRecently(key, val int) { x := Node{key, val, nil, nil} this.cache.AddLast(&x) this.m[key] = &x }
func (this *LRUCache) deleteKey(key int) { x := this.m[key] this.cache.Remove(x) delete(this.m, key) }
func (this *LRUCache) removeLeastRecently() { deletedNode := this.cache.RemoveFirst() k := deletedNode.Key delete(this.m, k) }
func Constructor(capacity int) LRUCache { return LRUCache{make(map[int]*Node), NewList(), capacity} }
func (this *LRUCache) Get(key int) int { if _, ok := this.m[key]; !ok { return -1 } this.makeRecently(key) return this.m[key].Value }
func (this *LRUCache) Put(key int, value int) { if _, ok := this.m[key]; ok { this.deleteKey(key) this.addRecently(key, value) return } if this.cap == this.cache.Len { this.removeLeastRecently() } this.addRecently(key, value) }
|