class LRUCache{
struct ListNode//for LRU
{
int value;
int key;
ListNode* prev;
ListNode* next;
ListNode(int _key, int _value):key(_key), value(_value), prev(NULL), next(NULL){}
};
public:
LRUCache(int capacity) {
m_MaxCapacity = capacity;
m_head = NULL;
m_tail = NULL;
m_hashMap.clear();
}
int get(int key) {
auto it = m_hashMap.find(key);
if(it != m_hashMap.end())
{
move2Head(it->second);
return it->second->value;
}
else return -1;
}
void set(int key, int value) {
auto it = m_hashMap.find(key);
if(it != m_hashMap.end())//existed
{
ListNode* pCurNode = it->second;
pCurNode->value = value;
//attune current node before the head
move2Head(pCurNode);
}
else//not existed
{
if((int)m_hashMap.size() == m_MaxCapacity)
{
//first invalidate the least recently used item, e.g, delete the tail
deleteTail();
}
//insert before the head
insert2Head(key, value);
}
}
private:
void move2Head(ListNode* pCurNode)
{
if(pCurNode != m_head)
{
if(pCurNode == m_tail) m_tail = pCurNode->prev;
pCurNode->prev->next = pCurNode->next;
if(pCurNode->next != NULL) pCurNode->next->prev = pCurNode->prev;
pCurNode->prev = NULL;
m_head->prev = pCurNode;
pCurNode->next = m_head;
m_head = pCurNode;
}
}
void deleteTail()
{
if(m_tail != NULL)
{
int deleteKey = m_tail->key;
auto it = m_hashMap.find(deleteKey);
m_hashMap.erase(it);
ListNode* pDeleteNode = m_tail;
if(m_tail->prev != NULL) m_tail->prev->next = NULL;
else m_head = NULL;
m_tail = m_tail->prev;
delete pDeleteNode;
}
//else input capacity error
}
void insert2Head(int key, int value)
{
ListNode* pNewNode = new ListNode(key, value);
if(m_head != NULL)
{
m_head->prev = pNewNode;
pNewNode->prev = NULL;
pNewNode->next = m_head;
m_head = pNewNode;
}
else m_head = m_tail = pNewNode;
m_hashMap.insert(make_pair(key, pNewNode));
}
private:
unordered_map<int, ListNode*> m_hashMap;
ListNode* m_head;
ListNode* m_tail;
int m_MaxCapacity;
};
[LeetCode]LRU Cache
最新推荐文章于 2017-10-29 09:36:07 发布