Created
July 7, 2025 17:34
-
-
Save benrhine/8d33d794d13ac53e8af6720b6a099e15 to your computer and use it in GitHub Desktop.
LRUCache
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 { | |
private final int capacity; | |
private final LinkedHashMap<Integer, Integer> cache; | |
public LRUCache(int capacity) { | |
this.capacity = capacity; | |
this.cache = new LinkedHashMap<Integer, Integer>(capacity, 1, true) { | |
@Override | |
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) { | |
return size() > capacity; | |
} | |
}; | |
} | |
public int get(int key) { | |
return cache.getOrDefault(key, -1); | |
} | |
public void put(int key, int value) { | |
cache.put(key, value); | |
} | |
public int size() { | |
return this.cache.size(); | |
} | |
public LinkedHashMap<Integer, Integer> getCache() { | |
return this.cache; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment