如果設計一個LRU(最少訪問次數)

public class LRUCache146_2 {
    private Map<Integer, int[]> cache = null;
    private int capacity = 0;


    public LRUCache146_2(int capacity) {
        cache = new LinkedHashMap<>();
        this.capacity = capacity;
    }

    /**
     * 獲取key的值
     *
     * @param key key
     * @return value
     */
    public int get(int key) {
        if (cache.containsKey(key)) {
            int[] ints = cache.get(key);
            cache.remove(key);
            cache.put(key, ints);
            return ints[1];
        }
        return -1;
    }

    /**
     * 向LRU中插入值
     *
     * @param key   key
     * @param value value
     */
    public void put(int key, int value) {
        int[] arr = new int[]{key, value};
        //如果存在這個key就更新value
        if (cache.containsKey(key)) {
            cache.remove(key);
            cache.put(key, arr);
            return;
        }
        if (cache.size() < capacity) {
            cache.put(key, arr);
        } else if (cache.size() == capacity) {
            int deleteKey = cache.entrySet().iterator().next().getKey();
            cache.remove(deleteKey);
            cache.put(key, arr);
        }
    }
}

時間複雜度:O(1)

時間複雜度:O(n)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章