思路1: map+数组
因为要淘汰最长时间没有被访问的元素,这里用一个切片维护这个容量和访问时间,所以在put和get的时候都要更新切片元素数量
我用map储存了键值,用一个切片元素,put时淘汰末尾的元素 get的时候把key放入切片头,同时去掉原来位置的元素,即把这个元素移动到头部
put的时候分两种情况,一种是这个元素已经放入cache中了,这时候map直接更新这个值即可,同时维护的切片要和get做同样的操作,移位
如果没有放入,就直接加入map和切片中即可。
put最后一步要判断放入元素数量是否超过cap,如果超过就把切片尾元素删除
Code
type LRUCache struct {
Cap int
Cache map[int]int
CacheArr []int
}
func Constructor(capacity int) LRUCache {
return LRUCache{
Cap: capacity,
Cache: make(map[int]int),
CacheArr: make([]int, 0),
}
}
func (this *LRUCache) Get(key int) int {
if _, ok := this.Cache[key]; !ok {
return -1
}
this.CacheArr = append(this.CacheArr, key)
index := 0
for i,k := range this.CacheArr{
if k == key {
index = i
break
}
}
this.CacheArr = append(this.CacheArr[:index], this.CacheArr[index+1:]...)
// fmt.Println(this.Cache)
return this.Cache[key]
}
func (this *LRUCache) Put(key int, value int) {
_, ok := this.Cache[key]
this.Cache[key] = value
this.CacheArr = append(this.CacheArr, key)
if ok {
index := getIndex(key, this.CacheArr)
this.CacheArr = append(this.CacheArr[:index], this.CacheArr[index+1:]...)
}
// 要删除旧的
if len(this.CacheArr) > this.Cap {
delete(this.Cache, this.CacheArr[0])
this.CacheArr = this.CacheArr[1:]
}
// fmt.Println(this.Cache)
}
func getIndex(value int, arr []int) int {
for i, v := range arr {
if v == value {
return i
}
}
return 0
}