146. LRU Cache

本文介绍了一种使用哈希映射和双向链表解决LRU缓存问题的方法。通过维护一个双向链表和哈希映射,可以实现在O(1)的时间复杂度内完成get和put操作。文章详细解释了四种私有方法:addAfterHead、removeNode、moveToHead和popTail的功能及其实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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

Problem URL


Solution

实现LRU缓存

Using a hash map and a self-constructed double linked list to solve this problem. The double linked list node have key\val\pre\post.

We have four private methods

  • addAfterHead for add new cache
  • popTail() returns tail node for delete node when delete node when capacity is full.
  • moveToHead for search or update of a node. Which is implemented by removeNode() and moveTohead();
  • removeNode() remove a node in the double linked list. Used for poptail() and moveToHead();

The LRU cache has a map to map key to double linked list node. A head and a tail node for initail double linked list. A capacity and count;
Then get and put method would be very simple.

Code
class LRUCache {
    class DLinkedNode{
        int key;
        int val;
        DLinkedNode pre;
        DLinkedNode post;
    }
    
    private void addAfterHead(DLinkedNode node){
        node.post = head.post;
        node.pre = head;
        
        head.post.pre = node;
        head.post = node;
    }
    
    private void removeNode(DLinkedNode node){
        DLinkedNode pre = node.pre;
        DLinkedNode post = node.post;
        
        pre.post = post;
        post.pre = pre;
    }
    
    private void moveToHead(DLinkedNode node){
        this.removeNode(node);
        this.addAfterHead(node);
    }
    
    private DLinkedNode popTail(){
        DLinkedNode popOut = tail.pre;
        this.removeNode(popOut);
        return popOut;
    }
    
    private DLinkedNode head;
    private DLinkedNode tail;
    private int capacity;
    private int count;
    private Map<Integer, DLinkedNode> map;
    
    public LRUCache(int capacity) {
        this.count = 0;
        this.capacity = capacity;
        
        head = new DLinkedNode();
        head.pre = null;
        
        tail = new DLinkedNode();
        tail.post = null;
        
        head.post = tail;
        tail.pre = head;
        
        map = new HashMap<Integer, DLinkedNode>();
        
    }
    
    public int get(int key) {
        if (map.containsKey(key)){
            DLinkedNode res = map.get(key);
            this.moveToHead(res);
            return res.val;
            
        }
        else{
            return -1;
        }
    }
    
    public void put(int key, int value) {
        if (map.containsKey(key)){
            DLinkedNode update = map.get(key);
            update.val = value;
            this.moveToHead(update);
        }else{
            DLinkedNode insert = new DLinkedNode();
            insert.key = key;
            insert.val = value;
            map.put(key, insert);
            this.addAfterHead(insert);
            count++;
            if (count > capacity){
                DLinkedNode remove = this.popTail();
                map.remove(remove.key);
                count--;
            }
        }
    }
}

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

Time Complexity: O(1)
Space Complexity: O(capacity)


Review

A simple hard problem.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值