
javascript
/**
* @param {number} capacity
*/
var LRUCache = function (capacity) {
this.capacity = capacity
this.cache = new Map()
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function (key) {
if (this.cache.has(key)) {
const value = this.cache.get(key)
this.cache.delete(key)
this.cache.set(key, value)
return value
}
return -1
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function (key, value) {
if(this.cache.has(key)){
this.cache.delete(key)
}else if(this.cache.size>=this.capacity){
const firstKey = this.cache.keys().next().value
this.cache.delete(firstKey)
}
this.cache.set(key,value)
};
/**
* Your LRUCache object will be instantiated and called as such:
* var obj = new LRUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
解题思路
使用map来保存缓存对象,每次使用后都先删除原来的键值对,再重新增加,让他放在最后,使用this.cache.keys().next().value来获取第一个键值对的键,即最长时间未使用的
详细解法
1.在构造方法中定义最大缓存数量和缓存对象
2.在get方法中判断读取的键是否存在,存在就先删除原来的键值对,再重新增加,让他放在最后,然后换回他的值,不存在就返回-1
3.在put方法中判断读取的键是否存在,存在就先删除原来的键值对(更新使用情况),以及键值对数量是否超过限制,超过限制就删除第一个键值对,最后统一添加要添加的键值对