146. LRU 缓存 LRU算法(Java)

使用Java自带的哈希链表
具体见注释

class LRUCache {
    int cap;    //容量
    LinkedHashMap<Integer,Integer> cashe = new LinkedHashMap<>();
    public LRUCache(int capacity) {
        this.cap = capacity;    
    }
    public int get(int key) {
        //若不存在,返回-1
        if(!cashe.containsKey(key)){
            return -1;
        }
        //顺序跳前
        makeRecently(key);
        return cashe.get(key);
    }
    
    public void put(int key, int val) {
        //若已存在,修改val值后,顺序跳前
        if(cashe.containsKey(key)){
            cashe.put(key,val);
            makeRecently(key);
            return;
        }
        //否则插入
        //插入之前判断空间是否还够
        //若不足,找出最后一个移除
        if(cashe.size()>=this.cap){
            int oldestKey = cashe.keySet().iterator().next();
            cashe.remove(oldestKey);
        }
        cashe.put(key,val);      
    }
    
    private void makeRecently(int key){
        //获取值后移除,重新插入
        int val = cashe.get(key);
        cashe.remove(key);
        cashe.put(key,val);
    }
}



/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */

你可能感兴趣的:(算法,数据结构,java,算法,链表)