This question is not difficult once you know what is LRU cache . Check out the link if you don't know. A hashmap is used to record the key and value, and linkedlist can be used as a queue, the least recently used element is always the head one of this queue.
ublic class LRUCache {
private HashMap<Integer,Integer> cacheMap = null;
private LinkedList<Integer> cacheList = null;
private int cpct;
public LRUCache(int capacity) {
cpct = capacity;
cacheMap = new HashMap<Integer,Integer>();
cacheList = new LinkedList<Integer>();
}
public int get(int key) {
if(cacheMap.containsKey(key)) {
Integer val = cacheMap.get(key);
cacheList.remove(new Integer(key));
cacheList.add(key);
return (int)val;
}
return -1;
}
public void set(int key, int value) {
if(cacheList.size()<cpct){
if(cacheMap.containsKey(key)){
Integer val = cacheMap.get(key);
cacheList.remove(new Integer(key));
cacheList.add(key);
cacheMap.put(key,value);
}
else{
cacheMap.put(key,value);
cacheList.add(key);
}
}
else{// cache is full
if(cacheMap.containsKey(key)){
Integer val = cacheMap.get(key);
cacheList.remove(new Integer(key));
cacheList.add(key);
cacheMap.put(key,value);
}
else{
Integer keyOb = cacheList.poll();
cacheMap.remove(keyOb);
cacheMap.put(key,value);
cacheList.add(key);
}
}
}
}
Hello, welcome to Yizhe's Blog. I am Yizhe Liu, graduated from University of Arizona, with Master degree, major in Electrical and Computer Engineering. Actually, I am software guy. In my blog, many posts are about the Leetcode questions. I will post my ideas and implementations, which are accepted by Leetcode. If you have different opinions, please leave comment. I am happy to discuss with you. So lets start rocking them!!!
No comments:
Post a Comment