zoukankan      html  css  js  c++  java
  • LeetCode 146 LRU Cache 最近最少使用页面置换算法

    实现一个LRU缓存器,最近最少使用页面置换算法。缓存器主要有两个成员函数,get和set,其中get函数是通过输入key来获得value,如果成功获得后,这对(key, value)升至缓存器中最常用的位置(顶部),如果key不存在,则返回-1。set函数是插入一对新的(key, value),如果原缓存器中有该key,则需要先删除掉原有的,将新的插入到缓存器的顶部。如果不存在,则直接插入到顶部。若加入新的值后缓存器超过了容量,则需要删掉一个最不常用的值,也就是底部的值。具体实现时需要三个私有变量,cap, list和map,其中cap是缓存器的容量大小,list是保存缓存器内容的列表,map是哈希表,保存关键值key和缓存器各项的迭代器之间映射,方便以O(1)的时间内找到目标项。

     1 class LRUCache {
     2 public:
     3     LRUCache(int capacity) {
     4         cap=capacity;
     5     }
     6     
     7     int get(int key) {
     8         auto it=m.find(key);
     9         if(it==m.end())
    10             return -1;
    11         l.splice(l.begin(),l,it->second);
    12         return it->second->second;
    13     }
    14     
    15     void put(int key, int value) {
    16         auto it=m.find(key);
    17         if(it!=m.end())
    18             l.erase(it->second);
    19         l.push_front(make_pair(key,value));
    20         m[key]=l.begin();
    21         if(m.size()>cap)
    22         {
    23             int k=l.rbegin()->first;
    24             l.pop_back();
    25             m.erase(k);
    26         }
    27     }
    28 private:
    29     int cap;
    30     list<pair<int,int>> l;
    31     unordered_map<int,list<pair<int,int>>::iterator> m;
    32 };
    33 
    34 /**
    35  * Your LRUCache object will be instantiated and called as such:
    36  * LRUCache obj = new LRUCache(capacity);
    37  * int param_1 = obj.get(key);
    38  * obj.put(key,value);
    39  */
  • 相关阅读:
    使用Bootstrap模态框实现增删改查功能
    表中多个按钮进行操作不需要跳转页面的实现
    在调试javascript的时候,要常使用alert()
    Request.UrlReferrer 实现页面刷新
    确认框的使用。弹出一个确认框,Ajax提交一个请求,刷新页面。
    条件构造器queryWrapper和updateWrapper
    接口调用:从第三方接口获取数据
    Dictionary的用法
    数组和List之间的转换
    调用存储过程
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8504985.html
Copyright © 2011-2022 走看看