File tree Expand file tree Collapse file tree
algorithms/java/src/lruCache Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /*
2+ Analogous to the C++ solution at:
3+ https://github.com/haoel/leetcode/blob/625ad10464701fc4177b9ef33c8ad052d0a7d984/algorithms/cpp/LRUCache/LRUCache.cpp
4+ which uses linked list + hash map. But the Java stdlib provides LinkedHashMap
5+ which already implements that for us, making this solution shorter.
6+
7+ This could also be done by using, but that generates
8+ some inheritance boilerplate, and ends up taking the same number of lines:
9+ https://github.com/cirosantilli/haoel-leetcode/commit/ff04930b2dc31f270854e40b560723577c7b49fd
10+ */
11+
12+ import java .util .LinkedHashMap ;
13+ import java .util .Iterator ;
14+
15+ public class LRUCache {
16+
17+ private int capacity ;
18+ private LinkedHashMap <Integer ,Integer > map ;
19+
20+ public LRUCache (int capacity ) {
21+ this .capacity = capacity ;
22+ this .map = new LinkedHashMap <>();
23+ }
24+
25+ public int get (int key ) {
26+ Integer value = this .map .get (key );
27+ if (value == null ) {
28+ value = -1 ;
29+ } else {
30+ this .set (key , value );
31+ }
32+ return value ;
33+ }
34+
35+ public void set (int key , int value ) {
36+ if (this .map .containsKey (key )) {
37+ this .map .remove (key );
38+ } else if (this .map .size () == this .capacity ) {
39+ Iterator <Integer > it = this .map .keySet ().iterator ();
40+ it .next ();
41+ it .remove ();
42+ }
43+ map .put (key , value );
44+ }
45+ }
Original file line number Diff line number Diff line change 1+ import java .util .ArrayList ;
2+
3+ import org .junit .Test ;
4+ import static org .junit .Assert .*;
5+
6+ public class LRUCacheTest {
7+
8+ private LRUCache c ;
9+
10+ public LRUCacheTest () {
11+ this .c = new LRUCache (2 );
12+ }
13+
14+ @ Test
15+ public void testCacheStartsEmpty () {
16+ assertEquals (c .get (1 ), -1 );
17+ }
18+
19+ @ Test
20+ public void testSetBelowCapacity () {
21+ c .set (1 , 1 );
22+ assertEquals (c .get (1 ), 1 );
23+ assertEquals (c .get (2 ), -1 );
24+ c .set (2 , 4 );
25+ assertEquals (c .get (1 ), 1 );
26+ assertEquals (c .get (2 ), 4 );
27+ }
28+
29+ @ Test
30+ public void testCapacityReachedOldestRemoved () {
31+ c .set (1 , 1 );
32+ c .set (2 , 4 );
33+ c .set (3 , 9 );
34+ assertEquals (c .get (1 ), -1 );
35+ assertEquals (c .get (2 ), 4 );
36+ assertEquals (c .get (3 ), 9 );
37+ }
38+
39+ @ Test
40+ public void testGetRenewsEntry () {
41+ c .set (1 , 1 );
42+ c .set (2 , 4 );
43+ assertEquals (c .get (1 ), 1 );
44+ c .set (3 , 9 );
45+ assertEquals (c .get (1 ), 1 );
46+ assertEquals (c .get (2 ), -1 );
47+ assertEquals (c .get (3 ), 9 );
48+ }
49+ }
You can’t perform that action at this time.
0 commit comments