[Java] HashMap + Deque


  • 0
    N

    The below code has some logical problem, One test failed.
    I'm not able to correct it since I'm not able to see full input of test case. Can some one help me to understand where it's wrong ?

    Input ["LRUCache","put","put","put","put","put","get","put","get","get","put","get","put","put","put","get","put","get","get","get","get","put","put","get","get","get","put","put","get","put","get","put","get","get","get","put","put","put","get","put","get","get","put","put","get","put","put","put","put","get","put","put","get","put","put","get","put","put","put","put","put","get","put","put","get","put","get","get","get","put","get","get","put","put","put","put","get","put","put","put","put","get","get","get","put","put","put","get","put","put","put","get","put","put","put","get","get","get","put","put","put","put","get","put","put","put","put","put","put","put"]
    [[10],[10,13],[3,17],[6,11],[10,5],[9,10],[13],[2,19],[2],[3],[5,25],[8],[9,22],[5,5],[1,30],[11],[9,12],[7],[5],[8],[9],[4,30],[9.......

    public class LRUCache {
        private int capacity;
        private Map<Integer,Integer> keyValueMap;
        private Deque<Integer> deque;
        public LRUCache(int capacity) {
            this.capacity=capacity;
            keyValueMap = new HashMap<Integer,Integer>();
            deque = new LinkedList();
        }
        
        public int get(int key) {
            int val = -1;
            if(keyValueMap.containsKey(key)) {
                val = keyValueMap.get(key);
                if(deque.peekFirst()!=key) {
                    Boolean b = deque.remove(key);
                    /*System.out.println();
                    System.out.println("element "+key + " removed " + b);*/
    
                    deque.offerFirst(key);
                    /*for(int element : deque) {
                        System.out.print(" " + element);
                    }*/
                } 
            }                                
            return val;
        }
        
        public void put(int key, int value) {
            if(deque.size()==capacity) {
                
                if(keyValueMap.containsKey(key)) {
                    deque.remove(key);
                    deque.offerFirst(key);
                    keyValueMap.put(key,value);
                    return;
                }
                int k = deque.pollLast();
                keyValueMap.remove(k);
                
            }
            deque.offerFirst(key);
            keyValueMap.put(key,value);
        }
    }
    
    /**
     * Your LRUCache object will be instantiated and called as such:
     * LRUCache obj = new LRUCache(capacity);
     * int param_1 = obj.get(key);
     * obj.put(key,value);
     */
    
    

Log in to reply
 

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