LRU Cache

題目:
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

Follow up:
Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4</pre>

分析:
用2個hashmap
第1個hashmap keyValDict存儲key -> value and index(think of it as last access time)
第1個hashmap evictKeyDict存儲index -> key

實現get:
返回keyValDict.get(key),同時更新這個key的index = new index(new index is greater than any index)

實現put:
如果key exist, 修改key對應的value,并且更新key的index = new index(new index is greater than any index)
如果key not exist 那么插入新的元素,在插入之前先檢查一下capacity
如果capacity未滿,用keyValDict.put(key, {value, new index}), evictKeyDict.put(new index, key)插入。這里我們同時插入了兩個信息,一是key,value,二是這個key的index(last access time)

如果capacity已滿,刪除last_evict_index所指向的evictKeyDict的entry。同時刪除對應在keyValDict的entry。更新size。

時間復雜度是O(1)因為兩個函數都只是操作了hashmap

class LRUCache {
    class IntegerPair{
        public int val;
        public int index;
        public IntegerPair(int v, int i) {val = v; index = i;}
    }
    private int capacity, size, last_evict_index, assign_new_index;
    private HashMap<Integer, IntegerPair> keyValDict = new HashMap<Integer, IntegerPair>();
    private  HashMap<Integer, Integer> evictKeyDict = new HashMap<Integer, Integer>();

    public LRUCache(int capacity) {
        this.capacity = capacity;
        size = assign_new_index = 0;
        this.last_evict_index = -1;
    }

    public int get(int key) {
        IntegerPair ret = keyValDict.get(key);
        if(ret != null){
            int index = assign_new_index++;
            IntegerPair pair = new IntegerPair(ret.val, index);
            keyValDict.put(key, pair);
            evictKeyDict.remove(ret.index);
            evictKeyDict.put(index, key);
            return ret.val;
        }
        return -1;
    }

    public void put(int key, int value) {
        // If key already exists, just update
        IntegerPair ret = keyValDict.get(key);
        if(ret != null) {
            int index = assign_new_index++;
            IntegerPair pair = new IntegerPair(value, index);
            keyValDict.put(key, pair);
            evictKeyDict.remove(ret.index);
            evictKeyDict.put(index, key);
            return;
        }
        // If key not exist, insert, Check capacity first
        if(this.size == this.capacity) {
            Integer evictKey = null;
            this.last_evict_index++;
            while(last_evict_index < assign_new_index) {
                evictKey = evictKeyDict.get(last_evict_index);
                if(evictKey != null)
                    break;
                this.last_evict_index++;
            }
            keyValDict.remove(evictKey);
            evictKeyDict.remove(this.last_evict_index);
        }
        // Now, insert
        int index = assign_new_index++;
        IntegerPair pair = new IntegerPair(value, index);
        keyValDict.put(key, pair);
        evictKeyDict.put(index, key);
        if(size < capacity)
            size++;
    }
}

后來看了一下網絡上的解答,普遍是用以下思路

用一個hashmap,每個key指向一個double linked list node。Node里包含了value,next,prev等信息。每當一個元素被access/modify之后就把該node移動到頭部。如果要evict某個元素的話,直接移除double linked list的尾部就好了。

時間復雜度也是O(1), 因為hashmap的操作復雜度是O(1), 移動鏈表的node到頭部,刪除尾部node等操作也都是O(1)

import java.util.*;

class LRUCache {
    /*
        Data structure:

        Use hash map to store key -> node containing value

        When putting new element or accessing an element, we should put it to the front of list
        When reaching capacity, always remove the tail of list

    */
    public class DoublyListNode {
        int key;
        int val;
        DoublyListNode prev;
        DoublyListNode next;
        DoublyListNode(int key, int val) { this.key = key; this.val = val;}
    }

    // Current size of the list
    int size;

    // Current capacity of the list
    int capacity;

    // Doubly LinkedList for O(1) insert/remove
    DoublyListNode list_head;

    // Hashmap for O(1) access
    Map<Integer, DoublyListNode> map;

    public LRUCache(int capacity) {
        size = 0;
        this.capacity = capacity;
        list_head = new DoublyListNode(0, 0);
        DoublyListNode list_tail = new DoublyListNode(0, 0);


        list_head.next = list_tail;
        list_head.prev = list_tail;

        list_tail.next = list_head;
        list_tail.prev = list_head;

        map = new HashMap<>();
    }

    public void remove_node(DoublyListNode node) {
        DoublyListNode node_prev = node.prev;
        DoublyListNode node_next = node.next;

        node_prev.next = node.next;
        node_next.prev = node_prev;
    }

    public void insert_node(DoublyListNode node) {
        DoublyListNode prev_next = list_head.next;
        list_head.next = node;

        node.next = prev_next;
        node.prev = list_head;

        prev_next.prev = node;
    }

    public int get(int key) {
        DoublyListNode node = map.get(key);
        if(node == null) return -1;

        // Key exists
        int val = node.val;

        // Remove the node from wherever it was
        remove_node(node);

        // Insert the node to front
        insert_node(node);

        return val;
    }

    public void put(int key, int value) {
        DoublyListNode node = map.get(key);
        if(node == null) {
            node = new DoublyListNode(key, value);
            map.put(key, node);
        }
        else {
            node.val = value;
            // Remove the node from wherever it was
            remove_node(node);
            size--;
        }
        size++;
        // Before inserting anthing... check if capacity is full
        if(size > capacity) {
            // If capacity full, then remove tail
            map.remove(list_head.prev.prev.key);
            remove_node(list_head.prev.prev);
            size--;
        }

        // Insert the node to front
        insert_node(node);

    }
}


/**
 * 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);
 */

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,775評論 0 33
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,973評論 19 139
  • 題目描述:為最近最少使用緩存LRU Cache設計數據結構,它支持兩個操作:get和put。 get(key):如...
    Nautilus1閱讀 694評論 0 0
  • 沒想到自己真的完成了《堅持100天提升寫作計劃》的第一期, 這段時間來寫過的文字可能是5年甚至更長時間完成的字數。...
    oumiga_guan閱讀 315評論 0 2
  • VIM8+SpaceVIM 本文記錄了如何在ubuntu16.04 上編譯vim8(python3+,lua+),...
    qingguee閱讀 2,144評論 3 4