Accepted solution with LinkedHashMap


  • 0
    U

    public class LRUCache {
    LinkedHashMap<Integer, Integer> map;

    public LRUCache(int capacity) {
        
        map = new LinkedHashMap<Integer, Integer>(capacity) {
            protected boolean removeEldestEntry(Map.Entry en) {
                return size() > capacity;
            }
        };
    }
    
    public int get(int key) {
        Integer i = map.get(key);
        if (i == null) {
            return -1;
        } else {
            map.remove(key);
            map.put(key, i);
            return i;
        }
    }
    
    public void set(int key, int value) {
        if (map.get(key) != null) {
            map.remove(key);
        }
        map.put(key, value);
    }
    

    }


Log in to reply
 

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