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 DLNode struct { key, value int pre, next *DLNode }
type LRUCache struct { capacity int size int hashmap map[int]*DLNode head, tail *DLNode }
func DLNodeInit(key, value int) (*DLNode) { return &DLNode{ key: key, value: value, } }
func Constructor(capacity int) LRUCache { cache := LRUCache{ capacity: capacity, hashmap: map[int]*DLNode{}, head: DLNodeInit(0, 0), tail: DLNodeInit(0, 0), } cache.head.next = cache.tail cache.tail.pre = cache.head return cache }
func (this *LRUCache) Get(key int) int { if _, ok := this.hashmap[key]; ok { node := this.hashmap[key] this.removeToHead(node) return node.value } else { return -1 } }
func (this *LRUCache) Put(key int, value int) { if _, ok := this.hashmap[key]; !ok { if this.size < this.capacity { node := DLNodeInit(key, value) this.head.next, node.pre, node.next, this.head.next.pre = node, this.head, this.head.next, node this.hashmap[key] = node this.size++ } else { node := this.tail.pre delete(this.hashmap, node.key) node.key = key node.value = value this.removeToHead(node) this.hashmap[key] = node } } else { node := this.hashmap[key] this.removeToHead(node) node.value = value } }
func (this *LRUCache) removeToHead(node *DLNode) { node.pre.next, node.next.pre = node.next, node.pre this.head.next, node.pre, node.next, this.head.next.pre = node, this.head, this.head.next, node }
|