面試官:你能寫個LRU緩存嗎?

0. 前情提要

面試官: 你能手寫個LRU緩存嗎?
你: LRU是什麼東西?(一臉懵逼狀)
面試官: LRU全稱Least Recently Used(最近最少使用),用來淘汰不經常使用數據,保留熱點數據。
你寫了5分鐘,然而只寫了個get和put方法體,裏面邏輯實在不知道咋寫。
面試官: 今天的面試先到這吧,有其餘面試咱們會再聯繫你。
我信你個鬼,你個糟老頭子壞滴很,還聯繫啥,涼涼了。
別擔憂,再有人問你LRU,就把這篇文章丟給他,保證當場發offer。java

1. 實現思路

目的是把最不經常使用的數據淘汰掉,因此須要記錄一下每一個元素的訪問次數。最簡單的方法就是把全部元素按使用狀況排序,最近使用的,移到末尾。緩存滿了,就從頭部刪除。node

2. 使用哪一種數據結構實現?

經常使用的數據結構有數組、鏈表、棧、隊列,考慮到要從兩端操做元素,就不能使用棧和隊列。
每次使用一個元素,都要把這個元素移到末尾,包含一次刪除和一次添加操做,使用數組會有大量的拷貝操做,不適合。
又考慮到刪除一個元素,要把這個元素的前一個節點指向下一個節點,使用雙連接最合適。
鏈表不適合查詢,由於每次都要遍歷全部元素,能夠和HashMap配合使用。
雙鏈表 + HashMap面試

3. 代碼實現

import java.util.HashMap;
import java.util.Map;

/** * @author yideng */
public class LRUCache<K, V> {

    /** * 雙鏈表的元素節點 */
    private class Entry<K, V> {
        Entry<K, V> before;
        Entry<K, V> after;
        private K key;
        private V value;
    }

    /** * 緩存容量大小 */
    private Integer capacity;
    /** * 頭結點 */
    private Entry<K, V> head;
    /** * 尾節點 */
    private Entry<K, V> tail;
    /** * 用來存儲全部元素 */
    private Map<K, Entry<K, V>> caches = new HashMap<>();

    public LRUCache(int capacity) {
        this.capacity = capacity;
    }

    public V get(K key) {
        final Entry<K, V> node = caches.get(key);
        if (node != null) {
            // 有訪問,就移到鏈表末尾
            afterNodeAccess(node);
            return node.value;
        }
        return null;
    }

    /** * 把該元素移到末尾 */
    private void afterNodeAccess(Entry<K, V> e) {
        Entry<K, V> last = tail;
        // 若是e不是尾節點,才須要移動
        if (last != e) {
            // 刪除該該節點與前一個節點的聯繫,判斷是否是頭結點
            if (e.before == null) {
                head = e.after;
            } else {
                e.before.after = e.after;
            }

            // 刪除該該節點與後一個節點的聯繫
            if (e.after == null) {
                last = e.before;
            } else {
                e.after.before = e.before;
            }

            // 把該節點添加尾節點,判斷尾節點是否爲空
            if (last == null) {
                head = e;
            } else {
                e.before = last;
                last.after = e;
            }
            e.after = null;
            tail = e;
        }
    }

    public V put(K key, V value) {
        Entry<K, V> entry = caches.get(key);
        if (entry == null) {
            entry = new Entry<>();
            entry.key = key;
            entry.value = value;
            // 新節點添加到末尾
            linkNodeLast(entry);
            caches.put(key, entry);
            // 節點數大於容量,就刪除頭節點
            if (this.caches.size() > this.capacity) {
                this.caches.remove(head.key);
                afterNodeRemoval(head);
            }
            return null;
        }
        entry.value = value;
        // 節點有更新就移動到未節點
        afterNodeAccess(entry);
        caches.put(key, entry);
        return entry.value;
    }

    /** * 把該節點添加到尾節點 */
    private void linkNodeLast(Entry<K, V> e) {
        final Entry<K, V> last = this.tail;
        if (head == null) {
            head = e;
        } else {
            e.before = last;
            last.after = e;
        }
        tail = e;
    }

    /** * 刪除該節點 */
    void afterNodeRemoval(Entry<K, V> e) {
        if (e.before == null) {
            head = e.after;
        } else {
            e.before.after = e.after;
        }

        if (e.after == null) {
            tail = e.before;
        } else {
            e.after.before = e.before;
        }
    }

}
複製代碼

4. 其實還有更簡單的實現

import java.util.LinkedHashMap;
import java.util.Map;

/** * @author yideng */
public class LRUCache<K, V> extends LinkedHashMap<K, V> {

    // 最大容量
    private final int maximumSize;

    public LRUCache(final int maximumSize) {
        // true表明按訪問順序排序,false表明按插入順序
        super(maximumSize, 0.75f, true);
        this.maximumSize = maximumSize;
    }

    /** * 當節點數大於最大容量時,就刪除最舊的元素 */
    @Override
    protected boolean removeEldestEntry(final Map.Entry eldest) {
        return size() > this.maximumSize;
    }
}
複製代碼

爲啥繼承了LinkedHashMap,重寫了兩個方法,就實現了LRU?
下篇帶你手撕LinkedHashMap源碼,到時你會發現LinkedHashMap的源碼和上面一燈寫的LRU邏輯居然有驚人的類似。
數組

)
相關文章
相關標籤/搜索