LRU(双向链表和hash表)

 1 class LRUCache {
 2 public:
 3     struct Node
 4     {
 5         int    key;
 6         int    val;
 7         Node( int _k, int _v ) : key( _k ), val( _v )
 8         {
 9         }
10     };
11     list<Node>                    l;
12     unordered_map<int, list<Node>::iterator>    mp;
13     int                        size;
14     int                        capacity;
15     LRUCache( int _capacity ) : capacity( _capacity ), size( 0 )
16     {
17     }
18 
19 
20     int get( int key )
21     {
22         auto it = mp.find( key );
23         if ( it == mp.end() )
24             return(-1);
25         else{
26             int ans = it->second->val;
27             l.erase( it->second );
28             l.push_front( Node( key, ans ) );
29             it->second = l.begin();
30             return(ans);
31         }
32     }
33 
34 
35     void put( int key, int value )
36     {
37         auto it = mp.find( key );
38         if ( it != mp.end() )
39         {
40             l.erase( it->second );
41             l.push_front( Node( key, value ) );
42             it->second = l.begin();
43         }else  {
44             if ( size < capacity )
45             {
46                 l.push_front( Node( key, value ) );
47                 mp.insert( { key, l.begin() } );
48                 size++;
49             }else  {
50                 Node node = l.back();
51                 l.pop_back();
52                 auto rm = mp.find( node.key );
53                 mp.erase( rm );
54                 l.push_front( Node( key, value ) );
55                 mp.insert( { key, l.begin() } );
56             }
57         }
58     }
59 };

 

posted @ 2019-05-04 18:15  unique_ptr  阅读(952)  评论(0编辑  收藏  举报