LeetCode 解题报告 LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

分析:

这个题是一个思路扩展题,有很多东西是需要自己去添加的,而不是题目设定好的,这个题更能体现出答题者的思路是不是开阔来

首先我们思考把一个cache应该用map来寻址,然后就是表示他的访问量的问题,也就是LRU,可以用在链表的位置,如果在头部就说明刚刚被访问过,如果在尾部就说明在最近的一段时间他被访问的频率是最小,如果要有新的cache需要进入内存,那么就需要将其置换掉。

这里需要注意几个地方,一个是get方法,如果map中包含就将其取出,并且将其节点置换到首节点的位置,如果没有就返回-1

另一个是set方法,如果内存中已经有了,就更新value,并将此节点放入表头,如果没有还要分两种情况,一种是链表没满,就新new一个节点插入到表头,还有就是一种就是链表放满了,那么就新new一个节点插入表头,并将链表的最后一个节点删除

还有一个问题就是时间效率,一开始我直接用的List链表发现超时了,后来改成双向链表就好了

public class LRUCache {
    //Cache节点
    class CacheNode{
        CacheNode next;
        CacheNode pre;
        int k;
        int v;
        CacheNode(int k,int v){
            this.k = k;
            this.v = v;
        }
    }
    
    HashMap<Integer ,CacheNode> map;
    CacheNode head,tail;
    int size;
    
    public LRUCache(int capacity) {
        map = new HashMap<Integer,CacheNode>(capacity);
        size = capacity;
        head = new CacheNode(-1,-1);
        tail = new CacheNode(1,1);
        head.next = tail;
        tail.pre = head;
    }
    
    public int get(int key) {
        if(map.containsKey(key)){
            CacheNode p = map.get(key);
            putToHead(p);
            return p.v;
        }else{
            return -1;
        }
    }
    
    public void set(int key, int value) {
        if(map.containsKey(key)){
            CacheNode p = map.get(key);
            p.v = value;
            putToHead(p);
        }else if(map.size() < size){
            CacheNode p = new CacheNode(key,value);
            putToHead(p);
            map.put(key,p);
        }else{
            CacheNode p = new CacheNode(key,value);
            putToHead(p);
            map.put(key,p);
            int t = removeEnd();
            map.remove(t);
        }
    }
    private int removeEnd(){
        CacheNode p = tail.pre;
        tail.pre.pre.next = tail;
        tail.pre = tail.pre.pre;
        p.next = null;
        p.pre = null;
        return p.k;
    }
    private void putToHead(CacheNode p){
        if(p.next != null && p.pre != null){
            p.pre.next = p.next;
            p.next.pre = p.pre;
        }
        p.next = head.next;
        head.next.pre = p;
        head.next = p;
        p.pre = head;
        
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值