Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 27a92f7

Browse files
committed
lru cache: done
1 parent 9a10dad commit 27a92f7

File tree

2 files changed

+62
-1
lines changed

2 files changed

+62
-1
lines changed

‎src/main/java/com/leetcode/design/LFUCache.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
* Could you do both operations in O(1) time complexity?
2323
*
2424
* Note:
25-
* -
25+
* - When setting a key which is already present, reset its frequency/count to 1.
2626
*
2727
* @author rampatra
2828
* @since 2019年08月20日
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package com.leetcode.design;
2+
3+
import java.util.LinkedHashMap;
4+
import java.util.Map;
5+
6+
import static org.junit.jupiter.api.Assertions.assertEquals;
7+
8+
/**
9+
* Level: Medium
10+
* Link: https://leetcode.com/problems/lru-cache/
11+
* Description:
12+
* Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following
13+
* operations: get and put.
14+
*
15+
* get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
16+
* put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it
17+
* should invalidate the least recently used item before inserting a new item.
18+
*
19+
* The cache is initialized with a positive capacity.
20+
*
21+
* Follow up:
22+
* Could you do both operations in O(1) time complexity?
23+
*
24+
* Runtime: <a href="https://leetcode.com/submissions/detail/253383205/">54 ms</a>.
25+
*
26+
* @author rampatra
27+
* @since 2019年08月20日
28+
*/
29+
public class LRUCache {
30+
31+
private LinkedHashMap<Integer, Integer> cache;
32+
33+
public LRUCache(int capacity) {
34+
this.cache = new LinkedHashMap<Integer, Integer>(capacity, 0.75f, true) {
35+
@Override
36+
protected boolean removeEldestEntry(Map.Entry eldest) {
37+
return size() > capacity;
38+
}
39+
};
40+
}
41+
42+
public int get(int key) {
43+
Integer val = cache.get(key);
44+
return val == null ? -1 : val;
45+
}
46+
47+
public void put(int key, int value) {
48+
cache.put(key, value);
49+
}
50+
51+
public static void main(String[] args) {
52+
LRUCache cache = new LRUCache(2);
53+
cache.put(1,1);
54+
cache.put(2,2);
55+
cache.put(1,1);
56+
cache.put(3,3);
57+
assertEquals(1, cache.get(1));
58+
assertEquals(-1, cache.get(2));
59+
assertEquals(3, cache.get(3));
60+
}
61+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /