460. LFU Cache
Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and put.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value)
- Set or insert the value if the key is not already present. When the cache reaches its capacity, it should invalidate the least frequently used item before inserting a new item. For the purpose of this problem, when there is a tie (i.e., two or more keys that have the same frequency), the least recently used key would be evicted.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LFUCache cache = new LFUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.get(3); // returns 3.
cache.put(4, 4); // evicts key 1.
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
方法1: BST + hash
huahua: https://www.youtube.com/watch?v=MCTN3MM8vHA
思路:
Complexity
Time complexity: O(log capacity)
Space complexity: O(capacity)
struct CacheNode {
int key;
int value;
int freq;
long tick;
bool operator < (const CacheNode & rhs) const {
if (freq == rhs.freq) return tick < rhs.tick;
return freq < rhs.freq;
}
};
class LFUCache {
private:
int capacity_;
int tick_;
unordered_map<int, CacheNode> hash;
set<CacheNode> cache_;
// 一定要用 &
void touch(CacheNode & node) {
cache_.erase(node);
++node.freq;
node.tick = ++ tick_;
cache_.insert(node);
}
public:
LFUCache(int capacity) {
capacity_ = capacity;
tick_ = 0;
}
int get(int key) {
auto it = hash.find(key);
if (it == hash.end()) return -1;
int value = it -> second.value;
touch(it -> second);
return value;
}
void put(int key, int value) {
if (capacity_ == 0) return;
auto it = hash.find(key);
if (it != hash.end()) {
it -> second.value = value;
touch(it -> second);
return;
}
if (hash.size() == capacity_) {
CacheNode node = *cache_.begin();
hash.erase(node.key);
cache_.erase(node);
}
CacheNode node{key, value, 1, ++tick_};
hash[node.key] = node;
cache_.insert(node);
}
};
/**
* Your LFUCache object will be instantiated and called as such:
* LFUCache* obj = new LFUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
方法2: three hashmap
huahua: https://www.youtube.com/watch?v=MCTN3MM8vHA
grandyang: https://www.cnblogs.com/grandyang/p/6258459.html
discussion: https://leetcode.com/problems/lfu-cache/discuss/94516/Concise-C%2B%2B-O(1)-solution-using-3-hash-maps-with-explanation
思路:
这个题最关键的一个trick在于,在put的过程中将已经存在该key的case化简了:在改变其cache所在位置的步骤中,是完全和get重复的,如果存在(get (key)!= -1)我们在get之后只需要改一下val的值可以返回。那么剩下的问题就只有新put值的一种情况,在更新起来会方便很多。这里minfreq一开始不明白为什么一定会每次++,难道不应该找到下一个minfreq更新吗?这是因为minfreq始终追着一个freq最少的元素,每次出现minfreq的变化可能是两种情况:1. 新的元素进来了,所以minfreq = 1,2. 原来minfreq的一个元素被调用了,那么此时在将该元素从原来list删除后,必然会移至minfreq++的list中。所以可以正确update。
Complexity
Time complexity: O(1)
Space complexity: O(1)
class LFUCache {
private:
//minFreq is the smallest frequency so far
//The main idea is to put all keys with the same frequency to a linked list so the most recent one can be evicted;
//iter stored the key's position in the linked list;
int capacity_;
int minFreq;
unordered_map<int, pair<int, int>> m; ///key to {value,freq};
unordered_map<int, list<int>> freq; //freq to key list;
unordered_map<int, list<int>::iterator> iter; //key to list iterator;
public:
LFUCache(int capacity) {
capacity_ = capacity;
}
int get(int key) {
if (m.count(key) == 0) return -1;
// 在原freq list中删掉该key
freq[m[key].second].erase(iter[key]);
// m中freq自增1记录本次get
++m[key].second;
// push 到list最后,这样前面的就是同freq中应该最先删除的key
freq[m[key].second].push_back(key);
// 记录在新的freq list中的iter
iter[key] = --freq[m[key].second].end();
// 如果变动的是minFreq list中最后一个key,minFreq被拉高
if (freq[minFreq].size() == 0) ++minFreq;
return m[key].first;
}
void put(int key, int value) {
if (capacity_ <= 0) return;
// 如果key已经存在, 更新一下value
if (get(key) != -1) {
m[key].first = value;
return;
}
// 如果即将超过capacity
if (m.size() >= capacity_) {
// 从3个hash中去掉minFreq中按时间顺序访问最早的
m.erase(freq[minFreq].front());
iter.erase(freq[minFreq].front());
freq[minFreq].pop_front();
}
//更新3个hash
m[key] = {value, 1};
freq[1].push_back(key);
iter[key] = -- freq[1].end();
minFreq = 1;
}
};
/**
* Your LFUCache object will be instantiated and called as such:
* LFUCache* obj = new LFUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
有bug。
class LFUCache {
private:
int capacity_;
int minFreq;
unordered_map<int, list<pair<int, int>>::iterator> hash; ///key to {value,freq};
unordered_map<int, int> frequency; ///key to {value,freq};
unordered_map<int, list<pair<int, int>>> cache;
public:
LFUCache(int capacity) {
capacity_ = capacity;
}
int get(int key) {
if (hash.find(key) == hash.end()) return -1;
auto it = hash[key];
int freq = frequency[key]++;
int val = hash[key] -> second;
cache[freq].erase(it);
if (cache[freq].empty()) {
cache.erase(freq);
}
cache[freq + 1].push_front(make_pair(key, val));
hash[key] = cache[freq + 1].begin();
if (cache[minFreq].size() == 0) ++minFreq;
return val;
}
void put(int key, int val) {
if (capacity_ < 1) return;
if (get(key) != -1) {
hash[key] -> second = val;
return;
}
// 否则有可能超过capacity
if (hash.size() >= capacity_) {
int key_last = cache[minFreq].back().first;
cache[minFreq].pop_back();
hash.erase(key_last);
frequency.erase(key_last);
}
//更新3个hash
frequency[key] = 1;
cache[1].push_front(make_pair(key, val));
hash[key] = cache[1].begin();
minFreq = 1;
}
};