Skip to content

Instantly share code, notes, and snippets.

@snarkbait66
Created March 11, 2018 20:18
Show Gist options
  • Save snarkbait66/4c4a5e7f46e4fb7cb8ffb7a847632d2c to your computer and use it in GitHub Desktop.
Save snarkbait66/4c4a5e7f46e4fb7cb8ffb7a847632d2c to your computer and use it in GitHub Desktop.
LRU Cache - (LeetCode problem) using LinkedHashMap for O(1) time
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