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