Open chunbin1 opened 2 years ago
使用数组来记录key
class Cache {
constructor(size = 1) {
this.size = size
this.keyArr = []
this.keyValueMap = new Map()
}
get(key) {
debugger
const val = this.keyValueMap.get(key)
if (val) {
const idx = this.keyArr.indexOf(key)
this.keyArr.splice(idx, 1)
this.keyArr.unshift(key)
return val
}
return -1
}
put(key, val) {
if (this.keyValueMap.size >= this.size) {
// 缓存淘汰
const deleteKey = this.keyArr.pop()
this.keyValueMap.delete(deleteKey)
}
// 缓存进入
this.keyValueMap.set(key, val)
this.keyArr.push(key)
}
}
思路: 利用Map有顺序的原理
/**
/**
@return {void} */ LRUCache.prototype.put = function(key, value) { if(this.map.has(key)){ this.map.delete(key); } this.map.set(key,value); if(this.map.size > this.capacity){
} };
/**