/** * Your LRUCache object will be instantiated and called as such: * LRUCache* obj = new LRUCache(capacity); * int param_1 = obj->get(key); * obj->put(key,value); */
func(this *LRUCache) Get(key int) int { //返回迭代器 element, ok := this.mp[key] //如果 key 不存在则返回 -1 if !ok { return-1 } //提升为最近使用的,将该结点移动到链表头 this.lst.MoveToFront(element) return element.Value.(pair).value }
func(this *LRUCache) Put(key int, value int) { if element, ok := this.mp[key]; !ok { //key不存在 if this.lst.Len() == this.cap { //删除最久未使用的元素 back := this.lst.Back() this.lst.Remove(back) delete(this.mp, back.Value.(pair).key) } } else { //key已存在,抹去 this.lst.Remove(element) } //插入{key, value} newElement := this.lst.PushFront(pair{key: key, value: value}) //添加mp中 key 到 list迭代器的映射 this.mp[key] = newElement }
/** * Your LRUCache object will be instantiated and called as such: * obj := Constructor(capacity); * param_1 := obj.Get(key); * obj.Put(key,value); */