Least Recently Used (LRU) cache - leetcode

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?

Solution :
Forget about the O(1) solution, first you have to make it work properly!
There would be a list of Entry, the Entry has key, val, age. We can use position index to represent age, if use array of Entry to store data. When put or get, usually have to shift all elment. Not Efficient!
Try to use linked-list of Entry to store data, when put or get to update 'age' of entry, just need to change pointers. In this case, have to use head to record most recently used entry and tail to record least recently used entry, and use size and capacity to record if the list is full or not. And obviously double linked list is better since we have to record the current entry's pre entry to make it connect to current entry's post entry when remove current entry. In this way put and get would first try to find if key exist already or not, which is O(n) time complexity.
Think about doing space time trade-off, means using HashMap to record all the <key, Entry>. Thus, the entry retrival based on key would be O(1) time complexity.

Show me the code!

class LRUCache {
    class Entry{
        int key;
        int val;
        Entry post;
        Entry pre;
        public Entry(int key, int val){
            this.key = key;
            this.val = val;
            this.post = null;
            this.pre = null;
        }
    }
    
    Entry head;//record the newest item
    Entry tail;//record the oldest item
    Map<Integer, Entry> map = new HashMap<>();
        
    int capacity = 0;
    int size = 0;

    public LRUCache(int capacity) {
        this.capacity = capacity;
    }
    
    public int get(int key) {
        Entry entry = map.get(key);
        if(entry == null)
            return -1;
        adjustPst(entry);
        return entry.val;
    }
    
    public void put(int key, int value) {
        Entry entry = map.get(key);
        if(entry == null){
            if(size >= capacity){//remove tail if already full
                map.remove(tail.key);
                if(size == 1){
                    tail = null;
                    head = null;
                }else{
                    tail.pre.post = null;
                    tail = tail.pre;
                }
                size --;
            }
            entry = new Entry(key, value);
            if(head == null){
                head = entry;
                tail = entry;
            }else{
                entry.post = head;
                head.pre = entry;
                head = entry;
            }
            map.put(key, entry);
            size ++;
        }else{
            entry.val = value;
            adjustPst(entry);
        }
    }
    
    private void adjustPst(Entry entry){
        if(head != entry && tail != entry){
            entry.pre.post = entry.post;
            entry.post.pre = entry.pre;
            entry.pre = null;
            entry.post = head;
            head.pre = entry;
            head = entry;
        }else if(head != entry && tail == entry){
            tail = tail.pre;
            tail.post = null;
            entry.pre = null;
            entry.post = head;
            head.pre = entry;
            head = entry;
        }
        //do nothing if head == entry
    }
}

/**
 * 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)系作者
  • 序言:七十年代末税迷,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌联予,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,657評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡乒裆,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門推励,熙熙樓的掌柜王于貴愁眉苦臉地迎上來鹤耍,“玉大人肉迫,你說我怎么就攤上這事「寤疲” “怎么了喊衫?”我有些...
    開封第一講書人閱讀 164,057評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)杆怕。 經(jīng)常有香客問我格侯,道長(zhǎng),這世上最難降的妖魔是什么财著? 我笑而不...
    開封第一講書人閱讀 58,509評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮撑碴,結(jié)果婚禮上撑教,老公的妹妹穿的比我還像新娘。我一直安慰自己醉拓,他們只是感情好伟姐,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著亿卤,像睡著了一般愤兵。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上排吴,一...
    開封第一講書人閱讀 51,443評(píng)論 1 302
  • 那天秆乳,我揣著相機(jī)與錄音,去河邊找鬼钻哩。 笑死屹堰,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的街氢。 我是一名探鬼主播扯键,決...
    沈念sama閱讀 40,251評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼珊肃!你這毒婦竟也來了荣刑?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,129評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤伦乔,失蹤者是張志新(化名)和其女友劉穎厉亏,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體烈和,經(jīng)...
    沈念sama閱讀 45,561評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡叶堆,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了斥杜。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片虱颗。...
    茶點(diǎn)故事閱讀 39,902評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡沥匈,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出忘渔,到底是詐尸還是另有隱情高帖,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評(píng)論 5 345
  • 正文 年R本政府宣布畦粮,位于F島的核電站散址,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏宣赔。R本人自食惡果不足惜预麸,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望儒将。 院中可真熱鬧吏祸,春花似錦、人聲如沸钩蚊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽砰逻。三九已至鸣驱,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蝠咆,已是汗流浹背踊东。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留刚操,地道東北人递胧。 一個(gè)月前我還...
    沈念sama閱讀 48,025評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像赡茸,于是被迫代替她去往敵國(guó)和親缎脾。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評(píng)論 2 354

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