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.

Input:
2,[get(2),set(2,6),get(1),set(1,5),set(1,2),get(1),get(2)]
Output:
[-1,-1,2,6]  

  实现代码如下:

public class LRUCache {

    private int capacity;
    private HashMap<Integer,Node> hashMap = new HashMap<>();
    private Node head = new Node(-1,-1);
    private Node tail = new Node(-1,-1);

    private class Node {
        Node pre;
        Node next;
        int key;
        int value;

        Node(int key,int value) {
            this.key = key;
            this.value = value;
        }
    }

    public LRUCache(int capacity) {
        this.capacity = capacity;
        head.next = tail;
        tail.pre = head;
    }

    public int get(int key) {
        if(!hashMap.containsKey(key)) {
            return -1;
        }
        moveToHead(key);
        return hashMap.get(key).value;
    }

    public void set(int key, int value) {
        if(get(key) != -1) {
            hashMap.get(key).value = value;
            moveToHead(key);
            return;
        }
        if(hashMap.size() == capacity) {
            removeFromTail();
        }
        Node node = new Node(key,value);
        node.value = value;
        hashMap.put(key,node);

        node.next = head.next;
        head.next.pre = node;
        node.pre = head;
        head.next = node;

    }

    public void moveToHead(int key) {

        Node temp = hashMap.get(key);

        temp.pre.next = temp.next;
        temp.next.pre = temp.pre;

        temp.next = head.next;
        head.next.pre = temp;

        head.next = temp;
        temp.pre = head;

    }

    public void removeFromTail() {
        hashMap.remove(tail.pre.key);
        tail.pre.pre.next = tail;
        tail.pre = tail.pre.pre;
    }

}  

  稍微说明下。
  用HashMap可以快速判断链表中是否有要查找的节点以及要放入的节点在链表中是否已存在(是的话只要更新下值就行了)。
  设置头尾指针是因为LRU算法中要频繁用到将某节点插入或移到头部,或从尾部移除某个元素。
  用双向链表主要是为了操作时的效率,这样每次用HashMap找到相应节点后,直接在节点上操作就行了,没必要每次遍历到这个节点的前一个节点,然后再进行操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值