我想实现LFU(Least Freq Used),但是当缓存中所有项目的频率相同时,我希望以LRU(最近最少使用)的方式从缓存中删除该项目。
以下是代码:
class LFUCache {
int capacity;
int freq;int key,value;
long timeStamp; //needed for LRU
Map<Integer, LFUCache> hm = new HashMap<>();
Queue<LFUCache> queue = new PriorityQueue<>(new Comparator<LFUCache>(){
public int compare(LFUCache c1, LFUCache c2){
int freq1=c1.freq;
int freq2=c2.freq;
if(freq1<freq2){
return -1;
}else if(freq1>freq2){
return 1;
}else{
return Long.compare(c1.timeStamp, c2.timeStamp);
}
}
});
public LFUCache(int capacity) {
this.capacity = capacity;
}
public LFUCache(int key, int value){
this.key=key;
this.value=value;
}
public int get(int key) {
if(hm.containsKey(key)){
//cache hit
LFUCache item = hm.get(key); //get the orignal item
int data = item.value;
queue.remove(item); //remove orignal item
item.freq++;
long time = System.currentTimeMillis();
item.timeStamp = time;
queue.add(item);//add again
hm.put(key,item);
return data;
}else{
return -1;//item not found in cache
}
}
public void put(int key, int value) {
if(capacity==0)return;
if(hm.containsKey(key)){
//cache hit
LFUCache item = hm.get(key);
queue.remove(item);
item.freq++;
item.value=value;
long time = System.currentTimeMillis();
item.timeStamp = time;
queue.add(item);
hm.put(key,item);
return;
}
if(capacity<=hm.size()){ //exceeded capacity so remove LFU item
//remove by using LRU and LFU
LFUCache item = queue.poll();
hm.remove(item.key);
}
//creating and adding new item
LFUCache cacheItem = new LFUCache(key,value);
cacheItem.freq=1;
long time = System.currentTimeMillis();
cacheItem.timeStamp = time;
queue.add(cacheItem);
hm.put(key,cacheItem);
}
}
我想尝试:LFUCache obj = new LFUCache(capacity);
和obj.put(key,value);
另外,我想以低于O(n)的复杂度实现get和put函数。