-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRU 缓存(English) [lru-cache-lcci].html
44 lines (17 loc) · 1.18 KB
/
LRU 缓存(English) [lru-cache-lcci].html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<p>Design and build a "least recently used" cache, which evicts the least recently used item. The cache should map from keys to values (allowing you to insert and retrieve a value associ­ated with a particular key) and be initialized with a max size. When it is full, it should evict the least recently used item.</p>
<p>You should implement following operations: <code>get</code> and <code>put</code>.</p>
<p>Get a value by key: <code>get(key)</code> - If key is in the cache, return the value, otherwise return -1.<br />
Write a key-value pair to the cache: <code>put(key, value)</code> - If the key is not in the cache, then write its value to the cache. Evict the least recently used item before writing if necessary.</p>
<p><strong>Example:</strong></p>
<pre>
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.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
</pre>