zoukankan      html  css  js  c++  java
  • LRU Cache

    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.

    思路:

    挺诡异的,明明写法一样,但是总是超时,以后再看是怎么回事吧。

    另外auto的用法不错。

    代码:

     1 class LRUCache
     2 {
     3     int m_Capacity;
     4     unordered_map<int, int> m_Cache;
     5     list<int> m_Recently;
     6 
     7     void touch(int key)
     8     {
     9         auto kiter = find(begin(m_Recently), end(m_Recently), key);
    10         m_Recently.erase(kiter);
    11         m_Recently.push_front (key);
    12     }
    13 public:
    14     LRUCache (int capacity) : m_Capacity (capacity)
    15     {}
    16     
    17     int get (int key)
    18     {
    19         auto iter = m_Cache.find (key);
    20         if (iter == end(m_Cache))
    21             return -1;  // not found
    22         else
    23         {
    24             touch(key);
    25             return iter->second;
    26         }
    27     }
    28     
    29     void set (int key, int value)
    30     {                                                                                                  
    31         auto iter = m_Cache.find (key);                                                                
    32                                                                                                        
    33         if (iter == end(m_Cache))
    34         {                        
    35             if  (m_Cache.size() >= m_Capacity)
    36             {
    37                 int last = m_Recently.back();                                                              
    38                 m_Recently.pop_back();                                                                     
    39                 m_Cache.erase (last);
    40             }
    41             m_Recently.push_front(key);
    42         }
    43                                                                                                        
    44         m_Cache[key] = value;
    45         touch(key);
    46     }
    47 };
  • 相关阅读:
    Netty实现原理浅析
    Netty
    JAVA调用Rest服务接口
    泛型约束
    RegisterStartupScript和RegisterClientScriptBlock的用法
    TFS 2010 使用手册(四)备份与恢复
    TFS 2010 使用手册(三)权限管理
    TFS 2010 使用手册(二)项目集合与项目
    TFS 2010 使用手册(一)安装与配置
    错误"Lc.exe 已退出,代码 -1 "
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3462017.html
Copyright © 2011-2022 走看看