LeetCode Notes_#146 LRU缓存机制

LeetCode Notes_#146 LRU缓存机制

Contents

题目


解答

方法1

感觉这个题目挺有意思,我用HashMap实现了一个基本的解法,能通过除了一个大数据输入用例的其他所有用例,说明逻辑上是没有问题的。但是需要优化时间复杂度。

class LRUCache {
    HashMap<Integer, Integer> container;
    HashMap<Integer, Integer> noVisitTimes;
    int cap;
    int longestNoUseKey;

    public LRUCache(int capacity) {
        container = new HashMap<>();
        noVisitTimes = new HashMap<>();
        cap = capacity;
        longestNoUseKey = -1;
    }
    
    public int get(int key) {
        if(container.size() == 0) return -1;
        for(Integer k: container.keySet()){
            if(k == key) noVisitTimes.put(key, 0);
            else noVisitTimes.put(k, noVisitTimes.getOrDefault(k, 0) + 1);
        }
        if(container.containsKey(key)) return container.get(key);
        return -1; 
    }
    
    public void put(int key, int value) {
        for(Integer k: container.keySet()){
            if(k == key) noVisitTimes.put(key, 0);
            else noVisitTimes.put(k, noVisitTimes.getOrDefault(k, 0) + 1);
        }
        if(container.containsKey(key)){
            container.put(key, value);
        }else{
            if(container.size() < cap){
                container.put(key, value);
            }else{
                int maxNoUseTimes = -1;
                for(Integer k: noVisitTimes.keySet()){
                    if(noVisitTimes.get(k) > maxNoUseTimes){
                        maxNoUseTimes = noVisitTimes.get(k);
                        longestNoUseKey = k;
                    }
                }
                container.remove(longestNoUseKey);
                noVisitTimes.remove(longestNoUseKey);
                container.put(key, value);
            }
        }
    }
}

复杂度分析

时间复杂度:对于get()put()的操作,每次都需要遍历一遍大小为container.size()hashmap,复杂度为O(n),n为container.size()
空间复杂度:O(n),借助了一个额外的noVisitTimes的hashmap,大小和container相同

方法2

待更新

原文地址:https://www.cnblogs.com/Howfars/p/14253138.html