【LeetCode】LRU Cache 解决报告
插話:只寫了幾個連續的博客,博客排名不再是實際“遠在千里之外”該。我們已經進入2一萬內。
再接再厲。油!
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:?get?and?set.
get(key)?- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(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.
設計并實現一個支持get和set操作的緩存:
get(key) - 存在時返回其值。否則返回-1。
set(key) - 不存在時插入新值。存在時更新其值。注意當容量滿時,需刪除最長時間沒有訪問的key。將其刪除。并插入新的key。
==================== Map+List 實現法 ====================
【思路】
用map結構實現<key, value>的存儲與讀取。
用一個list來記錄key被訪問時間的久遠。近期被訪問的放在list的最后。list中的第一個key表示最長時間沒被訪問的。
【Java代碼】
class LRUCache {HashMap<Integer, Integer> map;ArrayList<Integer> list;int capacity;public LRUCache(int capacity) {map = new HashMap<Integer, Integer>(capacity);list = new ArrayList<Integer>(capacity);this.capacity = capacity;}public int get(int key) {if (map.get(key) == null) return -1;list.remove(new Integer(key)); list.add(key);return map.get(key);}public void set(int key, int value) {if (map.get(key) != null) {//原來存在keymap.put(key, value);list.remove(new Integer(key)); list.add(key);} else {//原來不存在keyif (map.size() < capacity) {//容量不滿map.put(key, value);list.add(key);} else {//容量滿int leastkey = list.remove(0);list.add(key);map.remove(leastkey);map.put(key, value);}}} }【注意點】
題目要求是Least Recently Used,不僅 set 時要更新list,get 時也要更新list。
set 時。需先推斷map中有無該值,若沒有再推斷map是否滿了;假設反過來,即先推斷map是否為滿,再推斷map中有無該值。這樣就錯了。
由于假設map滿時,當中有該值。直接更新就好,而先推斷map是否為滿的話。就會導致刪除最長時間沒有被訪問的值。
【常規解法】
通經常使用的元素雙向鏈表來記錄不被訪問的時間最長,由于雙向鏈表可以O(1)達到一定時間內移動的節點,刪除頭和尾節點。
在上面的代碼list實現,其remove當實際遍歷整個list為了找到一個節點。
LeetCode沒有時間作要求,采訪中肯定會要求。
總結
以上是生活随笔為你收集整理的【LeetCode】LRU Cache 解决报告的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 哪些云计算企业能活下来
- 下一篇: 第1章 游戏之乐——快速找出故障机器