146 LRU Cache


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

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(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.

Follow up:
Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4

为了使查找、插入和删除都有较高的性能,这题的关键是要使用一个双向链表和一 个HashMap,因为:
HashMap保存每个节点的地址,基本保证在 O(1) 时间内查找节点双向链表能后在 O(1) 时间内添加和删除节点,单链表则不行

具体实现细节:
越靠近链表头部,表示节点上次访问距离现在时间最短,尾部的节点表示最近 访问最少
访问节点时,如果节点存在,把该节点交换到链表头部,同时更新hash表中该 节点的地址
插入节点时,如果cache的size达到了上限capacity,则删除尾部节点,同时要 在hash表中删除对应的项;新节点插入链表头部

ava中也有双向链表 LinkedList , 但是 LinkedList 封装的太深,没有能在 O(1) 时间内删除中间某个元素的API(C++的 list 有个 splice() , O(1), 所以本题C++可以放心使用 splice() ),于是我们只能自己实现一个双向链表。本题有的人直接用 LinkedHashMap ,代码更短,但这是一种偷懒做法,面试官一定会让你自己重新实现。

class LRUCache {
    private Node head;
    private Node end;
    private int capacity;
    private HashMap<Integer, Node> map;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        map = new HashMap<>();
    }
    
    public int get(int key) {
        if (map.containsKey(key)) {
            Node n = map.get(key);
            remove(n);
            setHead(n);
            return n.value;
        } else
            return -1;
    }
    
    public void put(int key, int value) {
        if (map.containsKey(key)) {
            Node n = map.get(key);
            n.value = value;
            remove(n);
            setHead(n);
        } else {
            Node created = new Node(key, value);
            if (map.size() >= capacity) {
                map.remove(end.key);
                remove(end);
                setHead(created);
            } else
                setHead(created);
            
            map.put(key, created);
        }
    }
    
    private void remove(Node n) {
        if (n.prev != null) {
            n.prev.next = n.next;
        } else
            head = n.next;
        
        if (n.next != null) {
            n.next.prev = n.prev;
        } else
            end = n.prev;
    }
    
    private void setHead(Node n) {
        n.prev = null;
        n.next = head;
        
        if (head != null)
            head.prev = n;
        
        head = n;
        
        if (end == null)
            end = head;
    }
}

class Node {
    int key;
    int value;
    Node prev;
    Node next;
    
    public Node(int key, int value) {
        this.key = key;
        this.value = value;
    }
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值