LeetCode進階-實戰之LRU緩存機制(阿里面試題)

閒聊

最近github上有個很火的面試相關的項目短短几天時間就進入了trending首頁,項目是關於國內幾家互聯網大公司的面試題以及答案,裏面有很多算法題都值得刷一刷。本篇主要講阿里面試題裏面的LRU緩存機制,github上附有答案,遺憾的是隻有python版和C++版本的,沒有Java版本的...無fuck說,Java但是世界排名第一的語言!!!node

阿里面試題-LRU緩存機制

LRU 緩存機制 設計和實現一個 LRU(最近最少使用)緩存數據結構,使它應該支持一下操做:get 和 put。 get(key) - 若是 key 存在於緩存中,則獲取 key 的 value(老是正數),不然返回 -1。 put(key,value) - 若是 key 不存在,請設置或插入 value。當緩存達到其容量時,它應該在插入新項目以前使最近最少使用的項目做廢。python

爲何要刷LeetCode?

LRU是Least Recently Used的縮寫,即最近最少使用。根據題意須要手寫一個LRU算法,事實上在LeetCode上搜LRU即可以搜到146. LRU Cache,對比下面試題是一摸同樣。爲了方便結果驗證,咱們直接來看LeetCode原題。git

原題

146. LRU Cache

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

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.面試

The cache is initialized with a positive capacity.算法

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

Example:bash

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數據結構

146. LRU緩存

設計和實現一個LRU(最近最少使用)的緩存機制。它能夠支持如下操做: get 和 put 。

獲取數據 get(key) - 若是 (key) 存在於緩存中,則獲取值(老是正數),不然返回 -1。 寫入數據 put(key, value) - 若是key不存在,則寫入其數據值。當緩存容量達到上限時,在寫入新數據以前刪除最近最少使用的數據,從而爲新的數據留出空間。

進階:

你可否在 O(1) 時間複雜度內完成?

例:

LRUCache cache = new LRUCache( 2 /* 緩存容量 */ );

cache.put(1, 1); cache.put(2, 2); cache.get(1); // 返回 1 cache.put(3, 3); // 該操做會使得key 2 做廢 cache.get(2); // 返回 -1 (未找到) cache.put(4, 4); // 該操做會使得key 1 做廢 cache.get(1); // 返回 -1 (未找到) cache.get(3); // 返回 3 cache.get(4); // 返回 4

  • 本題在LeetCode上在Design分類下

方法一:雙向鏈表隊列實現LRU

思路設計

考慮到題目中的最近最少,咱們顯然能聯想到使用隊列結構。結合題意,爲了儘量的提升插入和查找的效率,保證時間複雜度在O(1),最大程度的提升get和put的速度,必然要使用雙向鏈表隊列(單鏈表須要遍歷才能插入節點,時間複雜度高)。而在實現了雙向鏈表隊列結構以後還須要考慮兩點:一、插入數據put達到數量上限時,刪除最老節點(最長時間未被使用),即鏈表隊列的尾部節點,由於尾部節點是最晚插入的;二、獲取數據get到數據時,須要將當前獲取到的節點移動到隊列頭部,由於最近被使用了。

編碼實踐

public class LRUCache {
	/**
	 * 
	 * Node類用於抽象鏈表的節點
	 * key、value存儲鍵、值,
	 * before、after分別指向當前節點的先後Node節點;
	 *
	 */
	class Node {
		int key;
		int value;
		Node before;
		Node after;
	}
	
	/**
	 * 使用HashMap緩存Node節點
	 */
	private HashMap<Integer, Node> cache = new HashMap<Integer, Node>();
	/**
	 * 最大容量,超過capacity時繼續插入會觸發刪除最老未被使用的節點
	 */
	private int capacity;
	/**
	 * 頭節點、尾節點(注意這兩個節點不存儲實際的數據)
	 */
	private Node head, tail;

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

		head = new Node();
		head.before = null;

		tail = new Node();
		tail.after = null;

		head.after = tail;
		tail.before = head;
	}

	/**
	 * 將節點插入隊列頭部
	 * 
	 * @param node
	 */
	private void addToHead(Node node) {

		node.before = head;
		node.after = head.after;
		head.after.before = node;
		head.after = node;

	}

	/**
	 * 刪除隊列中的一個節點
	 * 
	 * @param node
	 */
	private void removeNode(Node node) {
		Node before = node.before;
		Node after = node.after;
		before.after = after;
		after.before = before;
	}

	/**
	 * 將節點移動到有效數據頭部
	 * 
	 * @param node
	 */
	private void moveToHead(Node node) {
		removeNode(node);
		addToHead(node);
	}

	/**
	 * 刪除有效數據尾節點
	 * 
	 * @return 尾節點
	 */
	private Node popTail() {
		Node res = tail.before;
		this.removeNode(res);
		return res;
	}

	public int get(int key) {
		Node node = cache.get(key);
		if (node == null) {
			return -1; // should raise exception here.
		}
		// 若是獲取到數據,則將獲取到的節點移動到隊列頭部;
		moveToHead(node);
		return node.value;
	}

	public void put(int key, int value) {
		Node node = cache.get(key);
		if (node == null) {
			Node newNode = new Node();
			newNode.key = key;
			newNode.value = value;
			cache.put(key, newNode);
			addToHead(newNode);
			if (cache.size() > capacity) {
				// 刪除隊尾有效數據節點
				Node tail = this.popTail();
				this.cache.remove(tail.key);
			}
		} else {
			node.value = value;
			// 在使用get方法獲取值以後,須要將當前獲取的節點移動到隊列頭部
			moveToHead(node);
		}
	}
}
複製代碼

說明

見代碼註釋

方法二:Java標準庫JDK裏的LinkedHashMap

思路

事實上Java標準庫裏提供了能夠直接使用的LRU思想的數據結構,即LinkedHashMap,其底層實現原理和方法一是一致的

編碼實踐

class LRUCache extends LinkedHashMap<Integer,Integer>  {
    private int capacity;
    
    public LRUCache(int capacity) {
        super(capacity, 0.75F,true);
        this.capacity = capacity;
    }
    
    public int get(int key) {
        return super.getOrDefault(key,-1);
    }
    
    public void put(int key, int value) {
        super.put(key,value);
    }
    
    @Override 
    public boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest){
        return size() > capacity;
    }
}
複製代碼

說明

LinkedHashMap提供了能夠覆寫的removeEldestEntry方法,removeEldestEntry方法的做用直接參考LinkedHashMap源碼:

/**
     * Returns <tt>true</tt> if this map should remove its eldest entry.
     * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after
     * inserting a new entry into the map.  It provides the implementor
     * with the opportunity to remove the eldest entry each time a new one
     * is added.  This is useful if the map represents a cache: it allows
     * the map to reduce memory consumption by deleting stale entries.
     *
     * <p>Sample use: this override will allow the map to grow up to 100
     * entries and then delete the eldest entry each time a new entry is
     * added, maintaining a steady state of 100 entries.
     * <pre>
     *     private static final int MAX_ENTRIES = 100;
     *
     *     protected boolean removeEldestEntry(Map.Entry eldest) {
     *        return size() &gt; MAX_ENTRIES;
     *     }
     * </pre>
     *
     * <p>This method typically does not modify the map in any way,
     * instead allowing the map to modify itself as directed by its
     * return value.  It <i>is</i> permitted for this method to modify
     * the map directly, but if it does so, it <i>must</i> return
     * <tt>false</tt> (indicating that the map should not attempt any
     * further modification).  The effects of returning <tt>true</tt>
     * after modifying the map from within this method are unspecified.
     *
     * <p>This implementation merely returns <tt>false</tt> (so that this
     * map acts like a normal map - the eldest element is never removed).
     *
     * @param    eldest The least recently inserted entry in the map, or if
     *           this is an access-ordered map, the least recently accessed
     *           entry.  This is the entry that will be removed it this
     *           method returns <tt>true</tt>.  If the map was empty prior
     *           to the <tt>put</tt> or <tt>putAll</tt> invocation resulting
     *           in this invocation, this will be the entry that was just
     *           inserted; in other words, if the map contains a single
     *           entry, the eldest entry is also the newest.
     * @return   <tt>true</tt> if the eldest entry should be removed
     *           from the map; <tt>false</tt> if it should be retained.
     */
    protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
        return false;
    }
複製代碼

大概意思是在新插入一個節點時,刪除最老的節點,在緩存數據時能夠用到(簡直是LRU思想的量身定作)。另外若是使用默認false的話,表示容器沒有限制大小,不刪除最老未被使用的節點,至關於使用普通的Map。

還能夠注意到註釋中有一段很醒目的demo寫法:

private static final int MAX_ENTRIES = 100;
	    
     protected boolean removeEldestEntry(Map.Entry eldest) {
        return size() &gt; MAX_ENTRIES;
     }

複製代碼

本題中因爲限制條件爲超過隊列最大值限制大小即開始刪除最老節點,所以使用size() > capacity判斷條件。注意到get方法不是直接調用而是使用的getOrDefault(key,-1)是因爲題目描述當get拿不到數據時默認返回-1。

彩蛋

觀察方法一手寫雙向鏈表的實現,addToHead將節點添加到頭部方法以及popTail刪除尾節點的方法,分別是添加節點到頭部第二個節點,以及刪除倒數第二個節點,這是爲何呢?這即是本篇的彩蛋。

結語

針對阿里的LRU面試題,本題分析了兩種解法。我的猜想阿里出題者的出題思路是考察LRU思想的理解,在理解思想的基礎上可能會進一步延伸到LinkedHashMap的源碼,LinkedHashMap熟悉了會僞裝不經意繼續深刻到它的父類HashMap,到了HashMap確定繼續會問你負載因子,Hash碰撞,紅黑樹裂變,左右旋扯完了HashMap再和你談談HashTable和區別...你會發現總有一處可能命中你的盲點,是否是細思極恐,哈哈~不要方,掃一掃,關注個人微信訂閱號,後續會有針對相似LinkedHashMap等比較重要​的數據結構的源碼分析系列文章,敬請期待!最後,若是以爲本文對你有所幫助或啓發那就來個贊吧0.0

掃一掃 關注個人微信訂閱號
相關文章
相關標籤/搜索