LeetCode 146. LRU Cache

LRU Cache

Medium
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.

The cache is initialized with a positive capacity.

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

题意

实现经典的LRU缓存类,要求存/取数据的put/get方法都是O(1)的

思路

LRU的英文全称是least recent used,即“最近最久未使用”。一个自然的想法是维护一个双向链表,每次更新或者访问一个key,就把这个key对应的链表节点放到链表头;如果达到缓存长度上限需要淘汰节点,则删除链表尾的元素。这两样操作都是O(1),但问题在于链表的查询操作是O(n),光有双向链表不能保证get方法O(1). 为此另一个很自然的想法是引入哈希表,键为key,值为对应的双向链表的节点,这样就可以实现通过key的O(1)复杂度的查找。
具体实现上有一个细节需要注意,由于引入了哈希表,因此淘汰节点时不仅要删除双向链表的尾节点,还需要删除哈希表中相应节点。为了实现O(1)的删除,需要知道被删除节点在哈希表中的键值,因此双向链表节点类中需要添加一个字段表示链表节点对应的key值。

代码

class LRUCache {
    // list node of dual linked list
    class ListNode {
        public int key, val;
        public ListNode pre, next;
        
        public ListNode(int key, int val, ListNode pre, ListNode next) {
            this.key = key;
            this.val = val;
            this.pre = pre;
            this.next = next;
        }
    }
    
    private int capacity;
    private int volumn;
    private HashMap<Integer, ListNode> map;
    private ListNode head;                  // dummy head of dual linked list
    private ListNode tail;                  // dummy tail of dual linked list

    public LRUCache(int capacity) {
        this.capacity = capacity;
        volumn = 0;
        map = new HashMap<Integer, ListNode>();
        head = new ListNode(0, 0, null, null);
        tail = new ListNode(0, 0, head, null);
        head.next = tail;
    }
    
    public int get(int key) {
        ListNode cur = map.get(key);
        if (cur == null) {
            return -1;
        }
        cur.pre.next = cur.next;
        cur.next.pre = cur.pre;
        cur.pre = head;
        head.next.pre = cur;
        cur.next = head.next;
        head.next = cur;
        // printList(head, tail);
        return cur.val;
    }
    
    public void put(int key, int value) {
        if (map.containsKey(key)) {
            ListNode cur = map.get(key);
            cur.val = value;
            cur.pre.next = cur.next;
            cur.next.pre = cur.pre;
            cur.pre = head;
            head.next.pre = cur;
            cur.next = head.next;
            head.next = cur;
            return;
        }
        ListNode cur = new ListNode(key, value, head, head.next);
        map.put(key, cur);
        head.next.pre = cur;
        head.next = cur;
        volumn++;
        if (volumn > capacity) {
            map.remove(tail.pre.key);
            tail.pre.pre.next = tail;
            tail.pre = tail.pre.pre;
            volumn--;
        }
        // printList(head, tail);
    }
    
    // for debug
    private void printList(ListNode head, ListNode tail) {
        head = head.next;
        while (head != tail) {
            System.out.print(head.val + ", ");
            head = head.next;
        }
        System.out.println();
    }
}

/**
 * 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);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值