146. LRU Cache(js)
Posted xingguozhiming
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了146. LRU Cache(js)相关的知识,希望对你有一定的参考价值。
146. LRU Cache
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and put
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.put(key, value)
- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
The cache is initialized with a positive capacity.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ ); cache.put(1, 1); cache.put(2, 2); cache.get(1); // returns 1 cache.put(3, 3); // evicts key 2 cache.get(2); // returns -1 (not found) cache.put(4, 4); // evicts key 1 cache.get(1); // returns -1 (not found) cache.get(3); // returns 3 cache.get(4); // returns 4
题意:构建一个类和一个数据结构LRUCache,有get和put两个方法,get方法用于获取LRUCache中的值,不存在返回-1;put方法用于向LRUCache存入数值,当达到它的容量时,替换最近最少使用的
代码如下:
/** * @param number capacity */ var LRUCache = function(capacity) this.capacity=capacity; this.count=0; this.head=null; this.tail=null; this.hashTable=; ; /** * @param number key * @return number */ LRUCache.prototype.get = function(key) if(this.hashTable[key]) const value=this.hashTable[key]; const prev , next=this.hashTable[key]; if(prev) prev.next=next; if(next) next.prev=prev || next.prev; if(this.tail===this.hashTable[key]) this.tail=prev || this.hashTable[key]; this.hashTable[key].prev=null; if(this.head!==this.hashTable[key]) this.hashTable[key].next=this.head; this.head.prev=this.hashTable[key]; this.head=this.hashTable[key]; return value; return -1; ; /** * @param number key * @param number value * @return void */ LRUCache.prototype.put = function(key, value) if(this.hashTable[key]) this.hashTable[key].value=value; this.get(key); else this.hashTable[key]=key,value,prev:null,next:null; if(this.head) this.head.prev=this.hashTable[key]; this.hashTable[key].next=this.head; this.head=this.hashTable[key]; if(!this.tail) this.tail=this.hashTable[key]; this.count++; if(this.count>this.capacity) let removeKey=this.tail.key; if(this.tail.prev) this.tail.prev.next=null; this.tail=this.tail.prev; this.hashTable[key].prev=null; delete this.hashTable[removeKey]; this.count--; ; /** * Your LRUCache object will be instantiated and called as such: * var obj = Object.create(LRUCache).createNew(capacity) * var param_1 = obj.get(key) * obj.put(key,value) */
以上是关于146. LRU Cache(js)的主要内容,如果未能解决你的问题,请参考以下文章