JAVA beats 97.34% using LinkedHashMap


  • 0
    F

    Because leetcode does not import LinkedHashMap by default, so I import java.util.LinkedHashMap manually.

    import java.util.LinkedHashMap;
    import java.util.Map;
    
    /**
     * Created by fhqplzj on 16-7-11 at 下午5:41.
     */
    public class LRUCache extends LinkedHashMap<Integer, Integer> {
        private int capacity;
    
        public LRUCache(int capacity) {
            super(capacity, 0.75f, true);
            this.capacity = capacity;
        }
    
        @Override
        protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
            return size() > capacity;
        }
    
        public int get(int key) {
            return getOrDefault(key, -1);
        }
    
        public void set(int key, int value) {
            put(key, value);
        }
    }

  • 0
    C

    Hi Fhqplzj, I think getOrDefault or put doesn't change the order in LinkedHashMap. Can you explain how it works?


  • 1
    F

    @coldknight The third parameter of the constructor of LinkedHashMap means accessOrder, by default, it is set to false, which means insertion order, we set it to true to use its access order. You can refer to the docs of the API for more details.


Log in to reply
 

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