Leetcode: 146. LRU Cache

凌晨1:24,转行中的程序媛,一边敷着面膜一边刷题,画面太美。
既然是在程序人生专栏,应该可以写一点与程序无关的东西。
感恩节长假,放松了四天,今天上班回家累的只想葛优躺,但是还得撑着伺候公主洗漱睡觉,眼睛都睁不开了,好想直接倒头就睡,可是看着临近的面试,不得不撑着。实在受不了,在沙发上睡了一会儿,起来接着刷

  1. LRU Cache
    这是个设计题。
    Cache一般有几种,分类主要是针对当Cache full的时候,怎么remove element,比如:
    https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
    FIFO (queue)
    LIFO(stack)
    LRU(least recently used)-remove最不常用的
    TLRU(Time aware least recently used )
    跟LRU比,引入了TTU(time to use)的概念,
    常用在 Information-centric networking (ICN), Content Delivery Networks (CDNs) and distributed networks in general
    The TLRU ensures that less popular and small life content should be replaced with the incoming content.
    MRU(most recently used)-remove 最常用的
    for random access patterns and repeated scans over large datasets (sometimes known as cyclic access patterns) MRU cache algorithms have more hits than LRU due to their tendency to retain older data
    还有很多种,参考上面的wikipage

对于这道题,要求get/set/delete least recent used item都用O(1),
所以首选就是unordered_map因为unodered_map是用hash实现的,hash的优势就是O(1) access time.
但是怎么track least recent used item呢?
这个是解决Cache 满的关键,这也是为什么要adopt list。discuss里面很多写法都是用double linkedlist,c++里list就是用double linkedlist实现的。
list的主要目的是为了把最近access的node放到list头。
自然结果就是,最不常用的node就在结尾,这样cache满的时候,只用pop_back最后的node就好了。
如何能把最近access的node放在list头呢?
step1: search the node
step2: remove the node
step3: insert to head
step1:
As we all know, search in linkedlist cost O(n). Therefore, use the Hash to find the node, which makes the step O(1).
insert to head cost O(1).
step2:
remove node是决定leetcode discuss里面都用double linkedlist的原因。
为什么用double linkedlist?
refer to discuss:
when remove a node (assume the node is found),
the double linkedlist needs only the node itself to remove it in O(1) without any other node’s info.
while the single linkedlist needs the pre node to remove the target node.
这个singe linkedlist remove node的观点还有待确认。对于single linkedlist remove node,一行就可以搞定了:*node = *node->next; 并不需要prenode。只是要考虑tail节点的话,需要加一个extra判断语句,然后就是要加free不用的节点以防止内存泄漏。

class LRUCache {
private:
    //saves the capacity
    int m_capacity;
    //use hash map to look for the key's corresponding nodes
    unordered_map<int,list<pair<int,int>>::iterator>m_map;
    //list actually is the double linked-list which manages the nodes insert and delete in O(1)
    list<pair<int,int>>m_list;
    
public:
    LRUCache(int capacity) {
        m_capacity = capacity;
    }
    
    int get(int key) {
        auto founditer = m_map.find(key);
        if(founditer == m_map.end())
        {
            return -1;
        }
        
        m_list.splice(m_list.begin(), m_list, founditer->second);
        return founditer->second->second;
    }
    
    void put(int key, int value) {
        auto founditer = m_map.find(key);
        if(founditer != m_map.end()) //if the new added nodes already exist
        {
            m_list.splice(m_list.begin(), m_list, founditer->second); //always move the new access nodes to front
            founditer->second->second = value; //update the value of the node
            return;
        }
        
        if(m_map.size() == m_capacity) //if capacity reached, remove the tail from the list and also removes the nodes in the map.
        {
            int key_to_del = m_list.back().first;
            m_list.pop_back();
            m_map.erase(key_to_del);
        }
        
        //no matter what, adds the new pair into the front of the list, and saves it into the map as well.
        m_list.emplace_front(key,value); 
        m_map[key] = m_list.begin();
    }
};

另一种写法,
instead of:auto founditer = m_map.find(key);
直接用m_map[key]。
区别就是:
1, founditer means m_map_iter. m_map_iter->first is key; m_map_iter->second is list iterator.
Therefore, in order to access the value, founditer->second->second is needed.
2, m_map[key] means the list iterator directly.
要比较起来的话,经常写c的人第二种更顺手。但是,作为一个c++的人,第一种更professional吧。
iterator的概念也是刷题的时候才发现很常用:
这个wiki的解释就很好:
https://en.wikipedia.org/wiki/Iterator
In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists. Various types of iterators are often provided via a container’s interface.

class LRUCache {
private:
    int m_capacity;
    list<pair<int, int>> m_list;
    unordered_map<int, list<pair<int,int>>::iterator>m_map;
    
        
public:
    LRUCache(int capacity) {
        m_capacity = capacity;    
    }
    
    int get(int key) {
        if(m_map.find(key) == m_map.end())
        {
            return -1;
        }
        m_list.splice(m_list.begin(), m_list, m_map[key]);
        return m_map[key]->second;
    }
    
    void put(int key, int value) {
        //auto founditer = m_map.find(key);
        if(m_map.find(key) != m_map.end())
        {
            m_map[key]->second = value;
            m_list.splice(m_list.begin(), m_list, m_map[key]);   
            return;
        }
        
        if(m_list.size() == m_capacity)
        {
            int key_to_del = m_list.back().first;
            m_list.pop_back();
            m_map.erase(key_to_del);
        }
        
        
        m_list.emplace_front(key, value);
        m_map[key] = m_list.begin();
        
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
给定一个整数数组 nums 和一个目标值 target,要求在数组中找出两个数的和等于目标值,并返回这两个数的索引。 思路1:暴力法 最简单的思路是使用两层循环遍历数组的所有组合,判断两个数的和是否等于目标值。如果等于目标值,则返回这两个数的索引。 此方法的时间复杂度为O(n^2),空间复杂度为O(1)。 思路2:哈希表 为了优化时间复杂度,可以使用哈希表来存储数组中的元素和对应的索引。遍历数组,对于每个元素nums[i],我们可以通过计算target - nums[i]的值,查找哈希表中是否存在这个差值。 如果存在,则说明找到了两个数的和等于目标值,返回它们的索引。如果不存在,将当前元素nums[i]和它的索引存入哈希表中。 此方法的时间复杂度为O(n),空间复杂度为O(n)。 思路3:双指针 如果数组已经排序,可以使用双指针的方法来求解。假设数组从小到大排序,定义左指针left指向数组的第一个元素,右指针right指向数组的最后一个元素。 如果当前两个指针指向的数的和等于目标值,则返回它们的索引。如果和小于目标值,则将左指针右移一位,使得和增大;如果和大于目标值,则将右指针左移一位,使得和减小。 继续移动指针,直到找到两个数的和等于目标值或者左指针超过了右指针。 此方法的时间复杂度为O(nlogn),空间复杂度为O(1)。 以上三种方法都可以解决问题,选择合适的方法取决于具体的应用场景和要求。如果数组规模较小并且不需要考虑额外的空间使用,则暴力法是最简单的方法。如果数组较大或者需要优化时间复杂度,则哈希表或双指针方法更合适。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值