LeetCode 146 LRU Cache

class LRUCache {
//创建一个私有的变量有序哈希map
private LinkedHashMap<Integer,Integer> cache; static class LRUCacheImpl extends LinkedHashMap<Integer,Integer>{ private int maxSize; public LRUCacheImpl(int capacity){ //这里指定maxsize为true,类似于HashMap和concurrentHashMap,最后一个参数true说明可以指定该hashmap的大小 super(capacity*2,0.75f,true); maxSize=capacity; } @Override protected boolean removeEldestEntry(Map.Entry<Integer,Integer> eldest){ return size()>maxSize; } } public LRUCache(int capacity) { cache=new LRUCacheImpl(capacity); } public int get(int key) { return cache.getOrDefault(key,-1); } public void put(int key, int value) { cache.put(key,value); } }

 

posted on 2019-03-13 22:28  LASP  阅读(128)  评论(0)    收藏  举报

导航