460-最少使用缓存

Description
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.

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(3);       // returns 3.
cache.put(4, 4);    // evicts key 1.
cache.get(3);       // returns 3
cache.get(4);       // returns 4

• get(key)-如果键存在，返回值，否则返回-1
• put(key, value)-若键存在，更新值，否则，插入。当存储的键的数量超过容量，需要在插入键之前将最小使用频率的键删除掉。就这个问题而言，如果有多个键的使用频率一样，那么删除最近最少使用的键。

• value, 存储键对应值
• count, 存储键对应的使用频率
• list, 存储使用频率对应的键的列表

class LFUCache {
//store <key, value> pair
Map<Integer, Integer> value;
//store <key, count> pair
Map<Integer, Integer> count;
//store <count, keylist> pair
//least frequent used count
int min = -1;
//capacity
int cap = 0;
public LFUCache(int capacity) {
cap = capacity;
value = new HashMap();
count = new HashMap();
list = new HashMap();
//注意这里
}

public int get(int key) {
//若键不存在，返回-1
if(!value.containsKey(key))    return -1;

int cnt = count.get(key);
//将频率增1
count.put(key, cnt + 1);
//删除频率列表中的key
list.get(cnt).remove(key);
//若min与cnt相等，说明当前最小使用频率为cnt
//若该频率对应键值列表为空，那么最小频率增1
if(min == cnt && list.get(cnt).size() == 0) min++;
//更新list
if(!list.containsKey(cnt + 1))  list.put(cnt + 1, new LinkedHashSet());

return value.get(key);
}

public void put(int key, int value) {
if(cap <= 0)    return;
//若包含key,调用get()进行更新，别忘了更新键对应的值
if(this.value.containsKey(key)){
this.value.put(key, value);
get(key);
return;
}
//若超过容量，删除min对应的键列表的第一个键,并且更新value和count
if(this.value.size() >= cap){
int evit = list.get(min).iterator().next();
list.get(min).remove(evit);
this.value.remove(evit);
count.remove(evit);
}

this.value.put(key, value);
//由于插入了一个新元素，当前最小使用频率必然是1
min = 1;
count.put(key, 1);
*/