LRU的实现(手撕)

手撕LRU

解题思路

  • LinkedList储存key值,实现最近最少使用。
  • get:如果存在该key,则先把LinkedList中原来的key值删除,再把key添加到LinkedList末尾,越最近使用的key越靠近LinkedList末尾。
  • put:如果存在该key,也要像get一样,先把LinkedList中原来的key值删除,再把key添加到LinkedList末尾,直接调用HashMap的put方法,新的value值就会覆盖旧的value值。
  • 如果put之前元素个数已经达到了容量,则把LinkedList中第一个元素删除,越是最近最少使用的key越靠近LinkedList头部。然后调用HashMap的put方法。
  • 不存在该key,也没有到达容量,直接调用HashMap的put方法。
class LRUCache {
    private int capacity;
    private HashMap<Integer,Integer> map;
    private LinkedList<Integer> list;
    public LRUCache(int capacity) {
        this.capacity=capacity;
        map=new HashMap<>();
        list=new LinkedList<>();
    }
    
    public int get(int key) {
        if(map.containsKey(key)){
            list.remove((Integer)key);
            list.addLast(key);
            return map.get(key);
        }
        return -1;
    }
    
    public void put(int key, int value) {
        if(map.containsKey(key)){
            list.remove((Integer)key);
            list.addLast(key);
            map.put(key,value);
            return;
        }
        if(list.size()==capacity){
            map.remove(list.removeFirst());
            map.put(key,value);
            list.addLast(key);
        }
        else{
            map.put(key,value);
            list.addLast(key);
        }
    }
}



import java.util.LinkedHashMap;
import java.util.Map;

public class LRU {
    class LRUCache extends LinkedHashMap<Integer, Integer> {
        private int capacity; //最多能缓存多少数据

        public LRUCache(int capacity) {
            //设置初始大小,负载因子
            //true指的是让LinkedHashMap按照访问顺序来进行排序,最近访问的放在头,最老访问的放在尾
            super(capacity, 0.75F, true);
            this.capacity = capacity;
        }

        public int get(int key) {
            return super.getOrDefault(key, -1);
        }

        public void put(int key, int value) {
            super.put(key, value);
        }

        // 当map中的数据量大于指定的缓存个数时,就自动删除最老的数据
        @Override
        protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
            return size() > capacity;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值