0146. LRU Cache

刷题内容

• https://leetcode.com/problems/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.put(4, 4);    // evicts key 1
cache.get(3);       // returns 3
cache.get(4);       // returns 4


解题方案

**- 时间复杂度: O(1)*- 空间复杂度: O(N)***

• 未超过存储上限时，每次put一个新数据时，向队列末尾插入当前key
• 每次get时，如果key存在，则将对应的key从的队列中，移到对末尾
• 在超过存储上限时，如进行put操作，则将队列首位删除掉

/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.limit = capacity || 2
this.storage = {}
this.keyList = []
};

/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
if (this.storage.hasOwnProperty(key)) {
let index = this.keyList.findIndex(k => k === key)
this.keyList.splice(index, 1)
this.keyList.push(key)
return this.storage[key]
} else {
return -1
}
};

/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
// 判断容量
if (this.keyList.length >= this.limit && !this.storage.hasOwnProperty(key)) {
this.deleteLRU()
}

// 存储数据
this.updateKeyList(key)
this.storage[key] = value
};

LRUCache.prototype.deleteLRU = function () {
delete this.storage[this.keyList.shift()]
}

LRUCache.prototype.updateKeyList = function (key) {
if (this.storage.hasOwnProperty(key)) {
var index = this.keyList.findIndex(k => key === k)
this.keyList.splice(index, 1)
}
this.keyList.push(key)
}

/**
* 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)
*/