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:
1 2 3 4 5 6 7 8 9 10 11
LRUCache cache = new LRUCache( 2 /* capacity */ );
LRUCache.prototype.deleteLRU = function () { deletethis.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) */