运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
题解:
1. 利用Map 的链式结构,使得get 在O(1) 时间完成
2. 利用Map keys 总是按照插入先后顺序输出key的迭代器。** 记住是插入,不是更新
3. 每次取值或者更新值时,都通过delete + set,使其移动到链尾,这样链首的就是最久没有使用的。
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.capacity = capacity;
this.storage = new Map();
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
const value = this.storage.get(key);
if(this.storage.has(key)){
this.storage.delete(key);
this.storage.set(key, value );
}
return value || -1;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
if(this.storage.size >= this.capacity && !this.storage.has(key)){
const removeKey = this.storage.keys().next().value;
this.storage.delete(removeKey);
}
if(this.storage.has(key)) this.storage.delete(key);
this.storage.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)
*/