Least recently used (最近最少使用)
/*** @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 cache = this.cache;if (cache.has(key)) {let temp = cache.get(key)cache.delete(key);cache.set(key, temp);return temp;} else {return -1;}};/*** @param {number} key* @param {number} value* @return {void}*/LRUCache.prototype.put = function (key, value) {let cache = this.cache;if (cache.has(key)) {cache.delete(key);} else if (cache.size >= this.capacity) {cache.delete(cache.keys().next().value);}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)*/
- get:访问某key,访问完要将其放在最后的。若key存在,先保存value值,删除key,再添加key,最后返回保存的value值。若key不存在,返回-1
- put:新加一个key,要将其放在最后的。所以,若key已经存在,先删除,再添加。如果容量超出范围了,将map中的头部删除。
- map.keys()返回一个迭代器
- 这个迭代器调用next()方法,返回包含迭代器返回的下一个值,存在value属性中
函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。
LRU 缓存算法的核心数据结构就是哈希链表,双向链表和哈希表的结合体。这个数据结构长这样:
