https://leetcode-cn.com/problems/lru-cache/
[brainstorm]
1 map structure for key, value pair.
2 remove least recent used, meaning earliest element, use list.
list keep item order.
3 while update/visit element, timestamp change. what we should do?
remove the corresponding item.
however, cannot locate which item, need to scan whole list.
4 to locate item, need structure for item index. can we do that?
[in summary] 3 structure
basic map for key, value pair
list for item order
structure for item index.
5 Three structure should be consistent.
[bug code]
class LRUCache {
Map<Integer, Integer> map;
List<Integer> list;
Map<Integer, Integer> indexes;
int cap;
int cnt=0;
public LRUCache(int capacity) {
map = new HashMap<>();
list = new ArrayList<>();
indexes = new HashMap<>();
this.cap = capacity;
}
public int get(int key) {
if(!map.containsKey(key)){
return -1;
}
list.remove(indexes.get(key));
list.add(key);
indexes.put(key, list.size()-1);
return map.get(key);
}
public void put(int key, int value) {
//not contain key
if(!map.containsKey(key)){
if(cnt==cap){
int k = list.get(0);
list.remove(0);
map.remove(k);
indexes.remove(k);
cnt--;
}
map.put(key, value);
list.add(key);
indexes.put(key, list.size()-1);
cnt++;
}
//contain key
map.put(key, value);
list.remove(indexes.get(key));
list.add(key);
indexes.put(key, list.size()-1);
}
}
/**
* 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);
*/