LeetCode146.LRU缓存机制(Java)

题目描述

https://leetcode-cn.com/problems/lru-cache/

AC代码

class LRUCache {
    private HashMap<Integer,Integer> map=new HashMap<>();
    private LinkedList<Integer> list=new LinkedList<>();
    private int cap;
    public LRUCache(int capacity) {
        this.cap=capacity;
    }
    
    public int get(int key) {
    	//不存在key,那么返回-1
        if(!map.containsKey(key)){
            return -1;
        }else{
        	//如果存在key,那么获取val值,然后删除掉原来的位置,放到最前面,因为热点访问
            int val=map.get(key);
            put(key,val);
            return val;
        }
    }
    
    public void put(int key, int value) {
    	//如果存在key,那么删除list中的旧值,在重新插入到list当中
    	//如果不存在key,看看有没有达到cap,如果有,那么需要删除很久没访问的那个元素,记得map和list都要删除,然后在map中添加key-val,list中添加key就好了。
        if(map.containsKey(key)){
            list.remove((Integer)key);
        }else{
            if(list.size()==cap){
                map.remove(list.removeFirst());
            }
        }
        map.put(key,value);
        list.add(key);
    }
}

/**
 * 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);
 */```

发布了201 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_40992982/article/details/105042705