Created
March 20, 2025 15:24
LRU (Least Recently Used) Cache
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
public class LRUCache { | |
private int capacity; | |
private Map<Integer, Integer> cache; | |
private LinkedHashMap<Integer, Long> accessTime; | |
public LRUCache(int capacity) { | |
this.capacity = capacity; | |
this.cache = new HashMap<>(); | |
this.accessTime = new LinkedHashMap<>(); | |
} | |
public int get(int key) { | |
if (!cache.containsKey(key)) { | |
return -1; | |
} | |
accessTime.put(key, System.nanoTime()); | |
return cache.get(key); | |
} | |
public void put(int key, int value) { | |
if (cache.size() >= capacity) { | |
long oldestTime = Long.MAX_VALUE; | |
int oldestKey = -1; | |
for (Map.Entry<Integer, Long> entry : accessTime.entrySet()) { | |
if (entry.getValue() < oldestTime) { | |
oldestTime = entry.getValue(); | |
oldestKey = entry.getKey(); | |
} | |
} | |
cache.remove(oldestKey); | |
accessTime.remove(oldestKey); | |
} | |
cache.put(key, value); | |
accessTime.put(key, System.nanoTime()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment