LRU(least recently used)

LRU(least recently used),最近最久未使用置换算法

是一种页面置换算法,操作系统中当内存空间不足时,会将内存中暂时不用的信息置换到外存(磁盘)中,用的时候再换进来。

所谓最近最久未使用置换算法就是优先将最近未使用(最早进来)的页面置换出去。根据局部性原理,认为最近使用的页面之后再次被使用的概率最大。因此该算法是合理的。

一种硬件解决方案是,对于每一个页面记录自上次访问经过的时间,置换时只需要置换该值最大的页面即可。然而该方式需要硬件电路的支持。

软件实现如下:

使用双端链表+哈希表的结构实现。需实现get(), put()方法。

使用双端链表维护从头到尾优先级递增。增加元素时在尾上加,删除元素时在头上删除。访问时,先通过hashmap找到该节点。然后将该节点从链表中删除,再加到尾部,如此保证了最近访问的优先级最高。

具体代码如下:

class LRUCache {
    public static class Node{
        int key;
        int val;
        Node pre;
        Node next;
        public Node(int key, int val){
            this.key = key;
            this.val = val;
        }
    } 
    private int capacity;
    private int length;
    private Map<Integer, Node> map;
    private Node head; // 从头到尾优先级递减
    private Node tail;
    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.length = 0;
        this.map = new HashMap<>();
        head = new Node(-1, -1);
        tail = new Node(-1, -1);
        head.next = tail;
        tail.pre = head;
    }
    
    public int get(int key) {
        if(!map.containsKey(key)){
            return -1;
        }
        Node cur = map.get(key);
        // 删除结点
        cur.pre.next = cur.next;
        cur.next.pre = cur.pre;
        // 插回到头上
        cur.pre = head;
        cur.next = head.next;
        head.next.pre = cur;
        head.next = cur;
        return cur.val;
    }
    
    public void put(int key, int value) {
        Node cur = null;
        if(map.containsKey(key)){
            cur = map.get(key);
            cur.val = value;
            get(key);
        }else{
            // 将该节点插到头上
            cur = new Node(key, value);
            map.put(key, cur);
            cur.pre = head;
            cur.next = head.next;
            head.next.pre = cur;
            head.next = cur;
            length++;
        }
        if(length > capacity){
            // 删除尾处的结点
            length--;
            Node temp = tail.pre;
            temp.pre.next = tail;
            tail.pre = temp.pre;
            temp.next = null;
            temp.pre = null;
            map.remove(temp.key);
        }
    }
}

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值