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 struct cacheNode
     2     {
     3         int key;
     4         int data;
     5     };
     6 
     7 class LRUCache{
     8 public:
     9     
    10     
    11     LRUCache(int capacity) 
    12     {
    13         size = capacity;
    14     }
    15     
    16     int get(int key) 
    17     {
    18         if( cacheMap.find(key) != cacheMap.end() )
    19         {
    20             list<cacheNode>:: iterator it = cacheMap[key];
    21             cacheList.splice(cacheList.begin(), cacheList, it);
    22             cacheMap[key] = cacheList.begin();
    23             return cacheList.begin()->data;
    24         }
    25         else
    26             return -1;
    27     }
    28     
    29     void set(int key, int value) 
    30     {
    31         if( cacheMap.find(key) != cacheMap.end() )
    32         {
    33             list<cacheNode>::iterator it = cacheMap[key];
    34             cacheList.splice(cacheList.begin(), cacheList, it);
    35             cacheMap[key] = cacheList.begin();
    36             cacheList.begin()->data = value;
    37         }
    38         
    39         else
    40         {
    41             if(cacheList.size() == size)
    42             {
    43                 cacheMap.erase(cacheList.back().key);
    44                 cacheList.pop_back();
    45             }
    46             
    47             cacheNode node;
    48             node.key = key;
    49             node.data = value;
    50             cacheList.push_front(node);
    51             cacheMap[key] = cacheList.begin();
    52         }
    53     }
    54     
    55 private:
    56     int size;
    57     list<cacheNode> cacheList;
    58     unordered_map<int, list<cacheNode>::iterator> cacheMap;
    59 };
  • 相关阅读:
    Linux基础篇之软件源码包安装
    11-1 网络协议和管理
    bash-2 httpd服务的源码编译安装脚本
    8-1 文本三级剑客之sed
    9-3 磁盘存储与分区
    9-2 yum,dnf和apt
    9-1 软件包管理
    bash-1 初始化CentOS系统的初始化脚本
    3-3 man手册介绍
    5-3 文件权限
  • 原文地址:https://www.cnblogs.com/YQCblog/p/3970209.html
Copyright © 2011-2022 走看看