When I got this problem, I used one Deque and one map to solve it, the solution is as following, the time complexity of get() and put() is O(n), n is the capacity. 

This solution will TLE under big data situation.

class LRUCache {
    private Map<Integer, Integer> map = new HashMap<>();
    private Deque<Integer> queue = new LinkedList<>();
    private int max;
    public LRUCache(int capacity) {
        max = capacity;
    }
    
    public int get(int key) {
        if(map.containsKey(key)){
            for(int i: queue){
                if(i==key){
                    queue.remove(i);
                    break;
                }
            }
            queue.push(key);
            return map.get(key);
        }
        else
            return -1;
    }
    
    public void put(int key, int value) {
        if(map.containsKey(key)){
            for(int i: queue){
                if(i==key){
                    queue.remove(i);
                    break;
                }
            }
        }
        else if(map.size()==max){
                int i =queue.getLast();
                queue.remove(i);
                map.remove(i);
        }
        queue.push(key);
        map.put(key, value);
    }
}

Actually, there is a "LinkedHashMap" in Java, we can use this "LinkedHashMap" to combine the function of Deque and HashMap, and make the time complexity of get() and put() to O(1).

class LRUCache {
    private LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>();
    private int max;
    public LRUCache(int capacity) {
        max = capacity;
    }
    
    public int get(int key) {
        if(map.containsKey(key)){
            int value = map.get(key);
            map.remove(key);
            map.put(key, value);
            return value;
        }else
            return -1;
    }
    
    public void put(int key, int value) {
        if(!map.containsKey(key)){
            if(map.size() == max){
                for(int i:map.keySet()){
                    map.remove(i);
                    break;
                }
            }
        }else
            map.remove(key);
        map.put(key, value);
    }
}

 

posted on 2022-02-07 11:31  阳光明媚的菲越  阅读(31)  评论(0编辑  收藏  举报