|
| 1 | +<h2><a href="https://leetcode.com/problems/lru-cache/">146. LRU Cache</a></h2><h3>Medium</h3><hr><div><p>Design a data structure that follows the constraints of a <strong><a href="https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU" target="_blank">Least Recently Used (LRU) cache</a></strong>.</p> |
| 2 | + |
| 3 | +<p>Implement the <code>LRUCache</code> class:</p> |
| 4 | + |
| 5 | +<ul> |
| 6 | + <li><code>LRUCache(int capacity)</code> Initialize the LRU cache with <strong>positive</strong> size <code>capacity</code>.</li> |
| 7 | + <li><code>int get(int key)</code> Return the value of the <code>key</code> if the key exists, otherwise return <code>-1</code>.</li> |
| 8 | + <li><code>void put(int key, int value)</code> Update the value of the <code>key</code> if the <code>key</code> exists. Otherwise, add the <code>key-value</code> pair to the cache. If the number of keys exceeds the <code>capacity</code> from this operation, <strong>evict</strong> the least recently used key.</li> |
| 9 | +</ul> |
| 10 | + |
| 11 | +<p>The functions <code>get</code> and <code>put</code> must each run in <code>O(1)</code> average time complexity.</p> |
| 12 | + |
| 13 | +<p> </p> |
| 14 | +<p><strong class="example">Example 1:</strong></p> |
| 15 | + |
| 16 | +<pre><strong>Input</strong> |
| 17 | +["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"] |
| 18 | +[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]] |
| 19 | +<strong>Output</strong> |
| 20 | +[null, null, null, 1, null, -1, null, -1, 3, 4] |
| 21 | + |
| 22 | +<strong>Explanation</strong> |
| 23 | +LRUCache lRUCache = new LRUCache(2); |
| 24 | +lRUCache.put(1, 1); // cache is {1=1} |
| 25 | +lRUCache.put(2, 2); // cache is {1=1, 2=2} |
| 26 | +lRUCache.get(1); // return 1 |
| 27 | +lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} |
| 28 | +lRUCache.get(2); // returns -1 (not found) |
| 29 | +lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} |
| 30 | +lRUCache.get(1); // return -1 (not found) |
| 31 | +lRUCache.get(3); // return 3 |
| 32 | +lRUCache.get(4); // return 4 |
| 33 | +</pre> |
| 34 | + |
| 35 | +<p> </p> |
| 36 | +<p><strong>Constraints:</strong></p> |
| 37 | + |
| 38 | +<ul> |
| 39 | + <li><code>1 <= capacity <= 3000</code></li> |
| 40 | + <li><code>0 <= key <= 10<sup>4</sup></code></li> |
| 41 | + <li><code>0 <= value <= 10<sup>5</sup></code></li> |
| 42 | + <li>At most <code>2 * 10<sup>5</sup></code> calls will be made to <code>get</code> and <code>put</code>.</li> |
| 43 | +</ul> |
| 44 | +</div> |
0 commit comments