Simple Java solution by extending LinkedHashMap and overriding removeEldestEntry!


  • 3
    N

    import java.util.LinkedHashMap;

    public class LRUCache extends LinkedHashMap<Integer, Integer> {

    private int capacity;
    
    public LRUCache(int capacity) {
    	super(capacity, 0.75f, true);
    	this.capacity = capacity;
    }
    
    public int get(int key) {
    	if (super.get(key) == null)
    		return -1;
    	return super.get(key);
    
    }
    
    public void set(int key, int value) {
    	super.put(key, value);
    }
    
    @Override
    protected boolean removeEldestEntry(
    		java.util.Map.Entry<Integer, Integer> eldest) {
    	// TODO Auto-generated method stub
    	return size() > capacity;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.