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
| type LRUCache struct { orderList []int cacheMaps map[int]int capacity int }
func Constructor(capacity int) LRUCache { return LRUCache{ orderList: make([]int, 0, capacity), cacheMaps: make(map[int]int, capacity), capacity: capacity, } }
func (this *LRUCache) Get(key int) int { if _, ok := this.cacheMaps[key]; ok { this.Update(key) return this.cacheMaps[key] } return -1 }
func (this *LRUCache) Update(key int) { for i := 0; i < len(this.orderList); i++ { if this.orderList[i] == key { this.orderList = append(this.orderList[:i], append(this.orderList[i+1:], this.orderList[i])...) } } }
func (this *LRUCache) Put(key int, value int) { if _, ok := this.cacheMaps[key]; ok { this.cacheMaps[key] = value this.Update(key) } else if len(this.cacheMaps) >= this.capacity { fmt.Println("=",len(this.orderList), len(this.cacheMaps), this.capacity) oldKey := this.orderList[0] this.orderList = this.orderList[1:] delete(this.cacheMaps, oldKey) this.cacheMaps[key] = value this.orderList = append(this.orderList, key) }else if len(this.cacheMaps) < this.capacity { fmt.Println("<", len(this.orderList), len(this.cacheMaps), this.capacity) this.cacheMaps[key] = value this.orderList = append(this.orderList, key) } }
|