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.

     1 class LRUCache{
     2 public:
     3     LRUCache(int capacity) {
     4         max_capacity = capacity;
     5         cur_size = 0;
     6     }
     7     
     8     int get(int key) {
     9         int value;
    10         if (hash.find(key) == hash.end()) {
    11             return -1;
    12         }
    13         else {
    14             auto it = hash[key];
    15             value = it->second;
    16             cache.push_front(*it);
    17             cache.erase(it); // delete
    18             
    19             hash[key] = cache.begin();
    20         }
    21         return value;
    22     }
    23     
    24     void set(int key, int value) {
    25            
    26         if (hash.find(key) != hash.end()) {
    27             cache.erase(hash[key]);
    28             hash.erase(key);        
    29         }
    30         else {
    31             if (cur_size < max_capacity) {
    32                 cur_size++;
    33             }
    34             else {
    35                 // delete old (key,value)
    36                 list<pair<int,int> >::iterator it = cache.begin();
    37                 advance(it, cur_size-1);
    38                 hash.erase(it->first);
    39                 cache.erase(it);
    40             }
    41         }
    42             
    43         cache.push_front(pair<int,int>(key,value));
    44         hash[key] = cache.begin();
    45     }
    46 
    47 private:
    48     int max_capacity;
    49     int cur_size;
    50     list<pair<int,int> > cache;
    51     unordered_map<int, list<pair<int,int> >::iterator> hash;
    52 };
  • 相关阅读:
    Filter 过滤器
    struts2 action接收请求参数和类型转换
    Struts2入门学习
    struts2请求参数校验
    IntelliJ IDEA 使用心得与常用快捷键
    关于动态代理详解
    web.xml文件详解
    关于mysql插入数据异常
    关于控制台输出 警告 log4j:WARN No appenders could be found for logger
    Hive load from hdfs 出错
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3629848.html
Copyright © 2011-2022 走看看