码迷,mamicode.com
首页 > 系统相关 > 详细

LRU Cache -- LeetCode

时间:2016-01-28 13:46:53      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(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.

思路:

 1 class LRUCache{
 2 public:
 3     class dlist
 4     {
 5         public:
 6             dlist *pre, *next;
 7             int key;
 8             dlist(int d, dlist *p, dlist *f) : key(d), pre(p), next(f){}
 9     };
10     int cap;
11     dlist *front, *tail;
12     unordered_map<int, int> data;
13     unordered_map<int, dlist *> addr;
14     LRUCache(int capacity) {
15         cap = capacity;
16         front = new dlist(0, NULL, NULL);
17         tail = new dlist(0, NULL, NULL);
18         front->next = tail;
19         tail->pre = front;
20     }
21     
22     int get(int key) {
23         if (data.count(key) == 0) return -1;
24         Delete(addr[key]);
25         AddtoTail(addr[key]);
26         return data[key];
27     }
28     void AddtoTail(dlist *node)
29     {
30         tail->pre->next = node;
31         node->pre = tail->pre;
32         node->next = tail;
33         tail->pre = node;
34     }
35     void Delete(dlist *node)
36     {
37         node->pre->next = node->next;
38         node->next->pre = node->pre;
39     }
40     void set(int key, int value) {
41         if (data.size() == cap && data.count(key) == 0)
42         {
43             if (front->next == tail) return;
44             data.erase(front->next->key);
45             addr.erase(front->next->key);
46             Delete(front->next);
47         }
48         if (data.count(key) == 0)
49         {
50             data.insert(make_pair(key, value));
51             dlist *ent = new dlist(key, NULL, NULL);
52             addr.insert(make_pair(key, ent));
53             AddtoTail(ent);
54         }
55         else
56         {
57             data[key] = value;
58             Delete(addr[key]);
59             AddtoTail(addr[key]);
60         }
61     }
62 };

 

LRU Cache -- LeetCode

标签:

原文地址:http://www.cnblogs.com/fenshen371/p/5165822.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!