首页 > 代码库 > LeetCode OJ - LRU Cache
LeetCode OJ - 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.
解题思路:
每一个Cache行有三个域(key, value, update_cnt);
用unordered_map来存储Cache体;
用queue来保存使用的历史信息。
代码:
struct Line { int key; int value; int update_cnt; }; class LRUCache{ public: int capacity; unordered_map<int, Line> cache; queue<Line> q; LRUCache(int capacity) { this->capacity = capacity; } int get(int key) { if (cache.count(key)) { cache[key].update_cnt++; q.push(cache[key]); return cache[key].value; } return -1; } void set(int key, int value) { if (cache.count(key)) { cache[key].value = value; cache[key].update_cnt++; q.push(cache[key]); } else { if (cache.size() == capacity) { Line tmp; while (!q.empty()) { tmp = q.front(); q.pop(); if (cache.count(tmp.key) && tmp.update_cnt == cache[tmp.key].update_cnt) { break; } } cache.erase(cache.find(tmp.key)); cache[key].key = key; cache[key].value = value; cache[key].update_cnt = 0; q.push(cache[key]); return; } cache[key].key = key; cache[key].value = value; cache[key].update_cnt = 0; q.push(cache[key]); } } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。