[Java] What's wrong with my code ?


  • 0
    A

    The test case that this fails on is very long and I can't seem to figure out what's wrong with the code.

    public class LRUCache {
        
        class Node{
            Node prev, next;
            int key, value;
            public Node(int key, int value){ this.key = key; this.value = value; }
        }
        
        Node head, tail;
        int capacity;
        
        void addFirst(Node node){
            if(head == null){
                head = tail = node;
            } else {
                head.prev = node;
                node.next = head;
                head = node;
            }
        }
        
        void remove(Node node){
            if(node == head) head = head.next;
            if(node == tail) tail = tail.prev;
            if(node.prev != null) node.prev.next = node.next;
            if(node.next != null) node.next.prev = node.prev;
        }
        
        void moveToFront(Node node){
            remove(node);
            addFirst(node);
        }
        
        void evictOne(){
            if(head == null) return;
            map.remove(tail.key);
            remove(tail);
        }
        
        Map<Integer, Node> map = new HashMap<>();
    
        public LRUCache(int capacity) { this.capacity = capacity; }
        
        public int get(int key) {
            Node node = map.get(key);
            if(node == null) return -1;
            moveToFront(node);
            return node.value;
        }
        
        public void put(int key, int value) {
            if(!map.containsKey(key) && map.size() == capacity) evictOne();
            Node node = map.get(key);
            if(node == null){
                node = new Node(key, value);
            } else {
                node.value = value;
            }
            map.put(key, node);
            moveToFront(node);
        }
    }
    
    

Log in to reply
 

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