1、题目
使用你所把握的数据结构,设计和实现一个 LRU (最近起码应用) 缓存机制 。
实现 LRUCache 类:
LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
void put(int key, int value) 如果关键字曾经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到下限时,它应该在写入新数据之前删除最久未应用的数据值,从而为新的数据值留出空间。
2、想法及实际
第一想到的是用数组(最相熟)来模仿队列,但最初的一个用例不能通过,爆栈了。
起初参考了题解,发现Map是有,获取最新的数据排列的办法 keys().next().value
参考思路,本人实现了,好使,记录一下
办法选错后,耗了俩个钟也搞不定,剖析思路解题计划还是挺重要的;
3、实现代码如下:
/** * @param {number} capacity */var LRUCache = function(capacity) { this.cache=new Map() this.capacity=capacity};/** * @param {number} key * @return {number} */LRUCache.prototype.get = function(key) { let res=-1 if(this.cache.has(key)){ res=this.cache.get(key) this.cache.delete(key) this.cache.set(key,res) } return res};/** * @param {number} key * @param {number} value * @return {void} */LRUCache.prototype.put = function(key, value) { if(this.cache.has(key)){ this.cache.delete(key) this.cache.set(key,value) }else{ // 判断容量下限 if(this.cache.size==this.capacity){ // 获取到增加程序的key值 const iteratorKey = this.cache.keys(); this.cache.delete(iteratorKey.next().value) } 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) */
参考链接
力扣链接