zoukankan      html  css  js  c++  java
  • 【Leetcode】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.

    双向链表 + hash map

     1 class LRUCache{
     2 public:
     3     LRUCache(int capacity) {
     4         this->capacity = capacity;
     5     }
     6     
     7     int get(int key) {
     8         if (cache_map.find(key) != cache_map.end()) {
     9             cache_list.splice(cache_list.begin(), cache_list, cache_map[key]);
    10             cache_map[key] = cache_list.begin();
    11             return cache_map[key]->value;
    12         } else {
    13             return -1;
    14         }
    15     }
    16     
    17     void set(int key, int value) {
    18         if (cache_map.find(key) != cache_map.end()) {
    19             cache_list.splice(cache_list.begin(), cache_list, cache_map[key]);
    20             cache_map[key] = cache_list.begin();
    21             cache_map[key]->value = value;
    22         } else {
    23             if (cache_list.size() == capacity) {
    24                 cache_map.erase(cache_list.back().key);
    25                 cache_list.pop_back();
    26             }
    27             cache_list.push_front(cacheNode(key, value));
    28             cache_map[key] = cache_list.begin();
    29         }
    30     }
    31 private:
    32     struct cacheNode {
    33         int key;
    34         int value;
    35         cacheNode(int key, int value) : key(key), value(value) {}
    36     };
    37     
    38     int capacity;
    39     unordered_map<int, list<cacheNode>::iterator> cache_map;
    40     list<cacheNode> cache_list;
    41 };
  • 相关阅读:
    JPA
    XMPP技术之Smack库的自定义消息扩展
    VMVare的窗口自适应
    linux c tcp p2p
    linux 消息队列
    基数排序-LSD
    基数排序-纪念欧某新
    归并排序
    锦标赛排序
    快速排序 之添加复合插入排序和原始序列取中值左pivot
  • 原文地址:https://www.cnblogs.com/dengeven/p/4004020.html
Copyright © 2011-2022 走看看