1. 程式人生 > 其它 >leetcode LRU快取機制 中等

leetcode LRU快取機制 中等

雙向連結串列維護 pair<key, value>,每次用到的一個 key 都把它放到連結串列頭部,容量滿時刪除連結串列尾部節點即可。

unordered_map<key, list<pair<key, value>>::iterator> 維護 key 與 連結串列節點的迭代器對映

class LRUCache {
public:
    LRUCache(int capacity):capacity(capacity) {

    }

    int get(int key) {
        if(map.find(key) != map.end()) {
            push_front(key);
            
return (*map[key]).second; } return -1; } void put(int key, int value) { if(map.find(key) != map.end()) { push_front(key); (*map[key]).second = value; } else { if(stack.size() >= capacity) { int eraseKey = stack.back().first; stack.pop_back(); map.erase(eraseKey); } stack.emplace_front(key, value); map[key]
= stack.begin(); } } private: void push_front(int key) { int val = (*map[key]).second; stack.erase(map[key]); stack.emplace_front(key, val); map[key] = stack.begin(); } int capacity; list<pair<int, int>> stack; // store key, val
unordered_map<int, list<pair<int, int>>::iterator> map; // key, ptr };