Java easy solution with LinkedList


  • 0
    Z

    The idea is similar to other posts. The only thing you need to think about is how to remove an int from LinkedList. Just use list.remove(new Integer(key)) and you are good to go.

    class LRUCache {
    
        Map<Integer, Integer> map;
        LinkedList<Integer> list;
        int capacity;
    
        public LRUCache(int capacity) {
            map = new HashMap<Integer, Integer>();
            list = new LinkedList<>();
            this.capacity = capacity;
        }
    
        public int get(int key) {
            if (map.containsKey(key)) {
                list.remove(new Integer(key));
                list.offer(key);
                return map.get(key);
            }
            return -1;
        }
    
        public void put(int key, int value) {
            if (map.containsKey(key)) {
                list.remove(new Integer(key));
            }
            list.offer(key);
            map.put(key, value);
    
            if (map.size() > capacity) {
                int first = list.poll();
                map.remove(first);
            }
        }
    }
    

Log in to reply
 

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