|
| 1 | +/** |
| 2 | + * 146. LRU Cache |
| 3 | + * https://leetcode.com/problems/lru-cache/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. |
| 7 | + * |
| 8 | + * Implement the LRUCache class: |
| 9 | + * - LRUCache(int capacity) Initialize the LRU cache with positive size capacity. |
| 10 | + * - int get(int key) Return the value of the key if the key exists, otherwise return -1. |
| 11 | + * - void put(int key, int value) Update the value of the key if the key exists. Otherwise, |
| 12 | + * add the key-value pair to the cache. If the number of keys exceeds the capacity from |
| 13 | + * this operation, evict the least recently used key. |
| 14 | + * |
| 15 | + * The functions get and put must each run in O(1) average time complexity. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number} capacity |
| 20 | + */ |
| 21 | +var LRUCache = function(capacity) { |
| 22 | + this.cache = new Map(); |
| 23 | + this.capacity = capacity; |
| 24 | +}; |
| 25 | + |
| 26 | +/** |
| 27 | + * @param {number} key |
| 28 | + * @return {number} |
| 29 | + */ |
| 30 | +LRUCache.prototype.get = function(key) { |
| 31 | + if (!this.cache.has(key)) { |
| 32 | + return -1; |
| 33 | + } |
| 34 | + |
| 35 | + const value = this.cache.get(key); |
| 36 | + this.cache.delete(key); |
| 37 | + this.cache.set(key, value); |
| 38 | + return this.cache.get(key); |
| 39 | +}; |
| 40 | + |
| 41 | +/** |
| 42 | + * @param {number} key |
| 43 | + * @param {number} value |
| 44 | + * @return {void} |
| 45 | + */ |
| 46 | +LRUCache.prototype.put = function(key, value) { |
| 47 | + if (this.cache.has(key)) { |
| 48 | + this.cache.delete(key); |
| 49 | + } |
| 50 | + this.cache.set(key, value); |
| 51 | + if (this.cache.size > this.capacity) { |
| 52 | + this.cache.delete(this.cache.keys().next().value); |
| 53 | + } |
| 54 | +}; |
0 commit comments