Skip to content

Instantly share code, notes, and snippets.

@duyng2512
Created March 20, 2023 04:51
Show Gist options
  • Save duyng2512/87e1f645bd98ba43fa712beaa576b8b6 to your computer and use it in GitHub Desktop.
Save duyng2512/87e1f645bd98ba43fa712beaa576b8b6 to your computer and use it in GitHub Desktop.
static class LRUCache {
LinkedHashMap<Integer, Integer> map;
// Linked List remain order of list
int cap;
public LRUCache(int capacity) {
this.cap = capacity;
map = new LinkedHashMap<>();
}
public int get(int key) {
if (!map.containsKey(key)) {
return -1;
}
int value = map.get(key);
map.remove(key);
map.put(key, value);
return value;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
map.remove(key);
map.put(key, value);
} else {
map.put(key, value);
if (map.size() > cap) {
// Remove first element
Integer firstKey = map.keySet().iterator().next();
map.remove(firstKey);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment