Thursday, January 16, 2014

LeetCode: 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.

Solution:

The easiest way to implement this cache is using a LinkedHashMap.

import java.util.LinkedHashMap;

public class LRUCache {
    int capacity;
    LinkedHashMap<Integer, Integer> cache;
    
    public LRUCache(int capacity) {
        cache = new LinkedHashMap<Integer, Integer>();
        this.capacity = capacity;
        
    }
    
    public int get(int key) 
    {
        int value = -1;
        if(cache.containsKey(key))
        {
            value = cache.get(key);
            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