Easy Java soln by Extending LinkedHashMap O(1)


  • 2
    A

    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) {
            super(capacity,(float)0.75,true);   
            //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) {
            put(key,value);
        }
        
        @Override
        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.