Sunday, January 11, 2015

LeetCode 146: LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
// The easiest solution of this question is to use 'LinkedHashMap'
// In 'LinkedHashMap', the elements are ordered by adding time.
import java.util.LinkedHashMap;

public class LRUCache {
    private Map<Integer, Integer> cache;
    private int capacity;
    
    public LRUCache(int capacity) {
        cache = new LinkedHashMap<>();
        this.capacity = capacity;
    }
    
    public int get(int key) 
    {
        int value = -1;
        
        if (cache.containsKey(key))
        {
            value = cache.get(key);
            
            // Note: 'get' operation changes 'the least recently used' order. So we should update the order.
            cache.remove(key);
            cache.put(key, value);
        }
        
        return value;
    }
    
    public void set(int key, int value) 
    {
        if (cache.containsKey(key))
            cache.remove(key);
        else if(cache.size()==capacity)
        {
            for (int firstKey : cache.keySet()) 
            {
                cache.remove(firstKey);
                break;
            }
        }
        
        cache.put(key, value);
    }
}

No comments:

Post a Comment