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個(gè)hashmap
第1個(gè)hashmap keyValDict存儲(chǔ)key -> value and index(think of it as last access time)
第1個(gè)hashmap evictKeyDict存儲(chǔ)index -> key

實(shí)現(xiàn)get:
返回keyValDict.get(key),同時(shí)更新這個(gè)key的index = new index(new index is greater than any index)

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

如果capacity已滿(mǎn),刪除last_evict_index所指向的evictKeyDict的entry。同時(shí)刪除對(duì)應(yīng)在keyValDict的entry。更新size。

時(shí)間復(fù)雜度是O(1)因?yàn)閮蓚€(gè)函數(shù)都只是操作了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++;
    }
}

后來(lái)看了一下網(wǎng)絡(luò)上的解答,普遍是用以下思路

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

時(shí)間復(fù)雜度也是O(1), 因?yàn)閔ashmap的操作復(fù)雜度是O(1), 移動(dòng)鏈表的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);
 */

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

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