20 Lines of Java code using LinkedHashSet O(1)


  • 0
    Y
    public class LRUCache {
        private HashMap<Integer, Integer> h_map = new HashMap<Integer, Integer>();
        LinkedHashSet<Integer> keys= new LinkedHashSet<Integer>();
        private int capacity=0;
        
        public LRUCache(int capacity) {
            this.capacity=capacity;
        }
        public int get(int key) {
            if(h_map.get(key)!=null){keys.remove(key);keys.add(key);return h_map.get(key);}
            return -1;
        }
        public void set(int key, int value) {
            if(capacity<=0) return;
            if(h_map.get(key)!=null) keys.remove(key);
            else if(h_map.size()==capacity) for(int i:keys){ keys.remove(i);h_map.remove(i);break;}
            keys.add(key);
            h_map.put(key,value);
        }
    }
    

Log in to reply
 

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