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 1:

public class LRUCache {
    
    Map<Integer,Integer> map;
    
    List<Integer> list;
    
    int cap;
    
    public LRUCache(int capacity) {
        map = new HashMap<>();
        list = new ArrayList<>();
        cap = capacity;
    }
    
    public int get(int key) {
        if(map.containsKey(key)){
            list.remove(list.indexOf(key));
            list.add(key);
            return map.get(key);
        } else {
            return -1;
        }
    }
    
    public void set(int key, int value) {
        if(map.containsKey(key)){
            map.put(key, value);
            list.remove(list.indexOf(key));
            list.add(key);
        } else {
            map.put(key, value);
            list.add(key);
            if(map.size()>cap){
                map.remove(list.get(0));
                list.remove(0);
            }
        }
    }
}
comments powered by Disqus