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