题目地址: 链接
思路: 利用 this.map.keys() 按照顺序存储特性并且 O(1) 时间复杂度完成存取,可以很好完成题目,并且 get 和 put 时间复杂度都为 O(1)
当前js 代码不能通过所有案例,有大佬能解释一下吗?
js
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.capacity = capacity;
this.map = new Map();
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
let ans = -1;
if(this.map.has(key)) {
ans = this.map.get(key);
this.map.delete(key);
this.map.set(key, ans);
}
return ans;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
if(this.map.has(key)) {
this.map.delete(key);
}
if(this.map.size >= this.capacity) {
let oldkey = this.map.keys().next().value;
this.map.delete(oldkey);
}
this.map.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)
*/