Easy Java soln by Extending LinkedHashMap O(1)

  • 2

    Passes all test cases. get/set in constant time.

    public class LRUCache extends LinkedHashMap<Integer, Integer>{
        private int capacity;
        public int getCapacity(){
            return capacity;
        public LRUCache(int capacity) {
            //LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)
            this.capacity = capacity;
        public int get(int key) {
            Integer value = super.get(key);
            return (value == null) ? -1 : value;
        public void set(int key, int value) {
        protected boolean removeEldestEntry(Map.Entry eldest){
            return size() > capacity ;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.