You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classLRUCache {
privateintcapacity;
privateMap<Integer, Integer> map;
privateList<Integer> list;
publicLRUCache(intcapacity) {
this.capacity = capacity;
this.map = newHashMap<>(capacity);
this.list = newLinkedList<>();
}
publicintget(intkey) {
// Get the value from the mapIntegervalue = this.map.get(key);
// The key does not existif (value == null) {
return -1;
}
// The key exists// Remove the key in the list and add it back to the endlist.remove((Integer) key);
list.addLast(key);
returnvalue;
}
publicvoidput(intkey, intvalue) {
// The key is already existsif (this.map.containsKey(key)) {
// Update the mapthis.map.put(key, value);
// Remove the key in the list and add it back to the endlist.remove((Integer) key);
list.addLast(key);
return;
}
// The key does not exist// The capacity is not enoughif (this.map.size() == this.capacity) {
IntegervictimKey = this.list.removeFirst();
this.map.remove(victimKey);
}
this.map.put(key, value);
this.list.addLast(key);
}
}