design and implement a data structure for least recently used (lru) cache. it should support the following operations: get and set.
<code>get(key)</code> - get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
<code>set(key, value)</code> - 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.
cache(高速緩存),需實作随機存取操作和高效的插入删除操作。
<code>vector</code>可以高效的随機存取,但是在插入删除會造成記憶體塊的拷貝。另外,當記憶體空間不夠時,需要重新申請一塊足夠大的記憶體并進行記憶體的拷貝。
<code>list</code>可以高效的插入删除,但是不支援随機存取。
<code>deque</code>支援随機存取,但是隻能在兩端進行插入删除操作。
是以采用雙向連結清單來實作插入删除操作,同時采用哈希表來實作高效的随機存取。在<code>unordered_map<key, value></code>中,<code>key</code>表示鍵值,<code>value</code>存儲該鍵值在連結清單中所對應的結點位置。
琢摸着感覺上述代碼效率還是偏低,于是把cache結點由一個struct結構體改為了一個pair,但是經過測試效果相當。以下是第二個版本的代碼: