Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class LRUCache {
- private:
- int cap;
- unordered_map<int, int> values, cnt;
- queue<int> order;
- public:
- LRUCache(int capacity) {
- cap = capacity;
- }
- int get(int key) {
- if (values.count(key) == 0)
- return -1;
- cnt[key]++;
- order.push(key);
- return values[key];
- }
- void put(int key, int value) {
- if ((int) values.size() >= cap && values.count(key) == 0) {
- while (cnt[order.front()] > 1) {
- cnt[order.front()]--;
- order.pop();
- }
- cnt[order.front()]--;
- values.erase(order.front());
- order.pop();
- }
- cnt[key]++;
- order.push(key);
- values[key] = value;
- }
- };
- /**
- * Your LRUCache object will be instantiated and called as such:
- * LRUCache* obj = new LRUCache(capacity);
- * int param_1 = obj->get(key);
- * obj->put(key,value);
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement