Implement LRU cache

Implement an LRU (Least Recently Used) cache. It should be able to be initialized with cache size, and contain the following methods:

  • set(key, value): sets key to value. If there are already n items in the cache and we are adding a new item, then it should also remove the least recently used item.
  • get(key): gets the value at key. If no such key exists, return null.

Each operation should run in O(1) time.

Example:

Input
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, null, -1, 3, 4]

Explanation
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1);    // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2);    // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1);    // return -1 (not found)
lRUCache.get(3);    // return 3
lRUCache.get(4);    // return 4

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

class LRUCache
{
public:
    int cap;
    vector<int> v;
    unordered_map<intint> mp;

    LRUCache(int capacity)
    {
        cap = capacity;
    }

    int get(int key)
    {
        auto pos = find(v.begin(), v.end(), key);
        if (pos != v.end())
        {
            v.erase(pos);
            v.push_back(key);
            return mp[key];
        }
        return -1;
    }

    void put(int keyint value)
    {
        auto pos = find(v.begin(), v.end(), key);
        if (pos != v.end())
            v.erase(pos);

        if (v.size() == cap)
        {
            mp[v[0]] = 0;
            v.erase(v.begin());
        }

        mp[key] = value;
        v.push_back(key);
    }
};

int main()
{
    LRUCache lRUCache(2);
    lRUCache.put(11);
    lRUCache.put(22);
    cout << "[";
    cout << lRUCache.get(1) << ", ";
    lRUCache.put(33);
    cout << lRUCache.get(2) << ", ";
    lRUCache.put(44);
    cout << lRUCache.get(1) << ", ";
    cout << lRUCache.get(3) << ", ";
    cout << lRUCache.get(4);
    cout << "]";

    return 0;
}


No comments:

Post a Comment