Friday, August 1, 2014

LRU Cache

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);
            }
        }
           
    }
}

No comments:

Post a Comment