Created
March 11, 2018 20:18
-
-
Save snarkbait66/4c4a5e7f46e4fb7cb8ffb7a847632d2c to your computer and use it in GitHub Desktop.
LRU Cache - (LeetCode problem) using LinkedHashMap for O(1) time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LRUCache { | |
class LRUMap<K, V> extends LinkedHashMap<K, V>{ | |
int size; | |
public LRUMap(int size) { | |
super(size, 0.75f, true); | |
this.size = size; | |
} | |
@Override | |
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { | |
return size() > size; | |
} | |
} | |
LRUMap<Integer, Integer> map; | |
public LRUCache(int capacity) { | |
map = new LRUMap<>(capacity); | |
} | |
public int get(int key) { | |
return map.getOrDefault(key, -1); | |
} | |
public void put(int key, int value) { | |
map.put(key, value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment