diff --git a/146.lru-cache.java b/146.lru-cache.java new file mode 100644 index 0000000..114a07d --- /dev/null +++ b/146.lru-cache.java @@ -0,0 +1,38 @@ +/* + * @lc app=leetcode id=146 lang=java + * + * [146] LRU Cache + */ + +// @lc code=start +class LRUCache { + private LinkedHashMap cache; + private int cap; + + public LRUCache(int capacity) { + this.cap = capacity; + cache = new LinkedHashMap<>(capacity, 0.75f, true) { + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return this.size() > cap; + } + }; + } + + public int get(int key) { + return cache.getOrDefault(key, -1); + } + + public void put(int key, int value) { + cache.put(key, value); + } +} + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache obj = new LRUCache(capacity); + * int param_1 = obj.get(key); + * obj.put(key,value); + */ +// @lc code=end +