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
| type LRUCache struct { Capacity int Map map[int]int List []int }
func Constructor(capacity int) LRUCache { return LRUCache{ Capacity : capacity, Map : make(map[int]int, 0), List : make([]int, 0), } }
func DelKey(a []int, key int) []int{ for i := 0; i < len(a); i++ { if a[i] == key { return append(a[:i], a[i+1:]...) } } return a[1:len(a)] }
func (this *LRUCache) Get(key int) int { if val, ok := this.Map[key]; ok{ this.List = DelKey(this.List, key) this.List = append(this.List, key) return val } return -1 }
func (this *LRUCache) Put(key int, value int) {
if _, ok := this.Map[key]; ok{ this.Map[key] = value this.List = DelKey(this.List, key) this.List = append(this.List, key) return }
if len(this.Map) >= this.Capacity{ delKey := this.List[0] this.List = DelKey(this.List, key) delete(this.Map, delKey) }
this.Map[key] = value this.List = append(this.List, key) }
|