Created
March 20, 2023 04:51
-
-
Save duyng2512/87e1f645bd98ba43fa712beaa576b8b6 to your computer and use it in GitHub Desktop.
This file contains 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
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