LRUCache实现的操蛋之路

定义

实现一个lru,意味着在一个容器里边,他有一个淘汰的size。达到这个size之后,再进行插入,则会把尾部的数据淘汰掉,这个就是容量淘汰。

146. LRU Cache

https://leetcode.com/problems/lru-cache/

实现方案

要实现这样一个数据结构,首先我们选择使用双端链表。
使用双端链表设计的必要性,在剔除尾巴节点的时候比较方便,理论上只要tail节点前移。
在访问当前节点的时候,可以拿到前后节点,然后放到header上,双端链表的优势是O(1)。


image.png

优化思路

为每一个节点建立索引,索引选择hashmap,只关注双端链表的操作,使得查询的时候不从头部遍历。

代码

public class LRUCache {
    private int size;
    private int capacity;
    private Entry header;
    private Entry tail;
    public LRUCache(int capacity) {
        if(capacity < 0){
            throw new IllegalStateException("capacity must not smaller than zero");
        }
        size = 0;
        this.capacity = capacity;
        header = new Entry();
        tail = header;
    }

    public void printList(){
        System.out.println("顺序");
        Entry e = header;
        while (e != null){
            System.out.print(e.getKey()+","+e.getValue()+" ");
            e = e.next;
        }
        System.out.println();
    }
    public void printListRevert(){
        System.out.println("逆序");
        Entry e = tail;
        while (e != null){
            System.out.print(e.getKey()+","+e.getValue()+" ");
            e = e.pre;
        }
        System.out.println();
    }

    public int get(int key) {
        Entry runner = header.next;
        while (runner != null && runner.getKey() != key){
            runner = runner.next;
        }
        if(runner == null || runner.getKey() != key){
            return -1;
        }else{
            Entry pre = runner.getPre();
            Entry next = runner.getNext();
            pre.next = next;
            if(next != null){
                next.pre = pre;
            }
            Entry first = header.getNext();
            header.next = runner;
            runner.pre = header;
            runner.next = first;
            if(first != null){
                first.pre = runner;
            }
            return runner.getValue();
        }
    }

    public void put(int key, int value) {
        Entry runner = header.getNext();
        while (runner != null && runner.getKey() != key){
            runner = runner.getNext();
        }
        if(runner == null){
            Entry newNode = new Entry();
            newNode.setKey(key);
            newNode.setValue(value);

            Entry first = header.next;
            header.next = newNode;
            newNode.pre = header;
            newNode.next = first;
            if(first != null){
                first.pre = newNode;
            }else{
                tail = newNode;
            }
            size ++;
        }else{
            runner.setValue(value);

            Entry pre = runner.getPre();
            Entry next = runner.getNext();

            pre.next = next;
            if(next != null){
                next.pre = pre;
            }

            Entry first = header.next;
            header.next = runner;
            runner.pre = header;
            runner.next = first;
            if(first != null){
                first.pre = runner;
            }else {
                tail = runner;
            }
        }
        afterHandler();
    }
    public void afterHandler(){
        if(size > capacity){
            while (tail.getNext() != null){
                tail = tail.next;
            }
            Entry e = tail.pre;
            e.next = null;
            tail.pre = null;
            tail = e;
            size --;
        }
        printList();
    }
    private static class Entry{

        private int key;
        private int value;

        private Entry next;
        private Entry pre;


        public Entry getPre() {
            return pre;
        }

        public void setPre(Entry pre) {
            this.pre = pre;
        }

        public int getKey() {
            return key;
        }

        public void setKey(int key) {
            this.key = key;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }

        public Entry getNext() {
            return next;
        }

        public void setNext(Entry next) {
            this.next = next;
        }

    }
}

数组版本

class LRUCache {
    private static class Entry{
        int key;
        int value;
    }
    private Entry[] data ;
    int capacity;
    int index;
    public LRUCache(int capacity) {
        if(capacity < 0){
            throw new IllegalStateException("capacity 要大于0");
        }
        this.capacity = capacity;
        data = new Entry[capacity];
        index = 0;
    }


    public int get(int key) {
        int index = findElementIndex(key);
        if(index == -1){
            return -1;
        }else {
            Entry e = data[index];
            if(index != 0){
                moveEntryWithDrop(0,index);
                data[0] = e;
            }
            return e.value;
        }
    }

    public void put(int key, int value) {
        int index = findElementIndex(key);
        if(index == -1){
            Entry newNode = new Entry();
            newNode.key = key;
            newNode.value = value;
            moveEntryWithDrop(0,data.length);
            data[0] = newNode;
            this.index ++;
        }else{
            Entry e = data[index];
            e.value = value;
            moveEntryWithDrop(0,index);
            data[0] = e;
        }
    }
    private void moveEntryWithDrop(int index,int len){
        if(index < data.length){
            Entry cur = data[index];
            Entry next = null;
            int i = index + 1;
            int times = 0;
            while (i < data.length && times < len){
                next = data[i];
                data[i] = cur;
                cur = next;
                i ++;
                times ++;
            }
        }
    }
    private int findElementIndex(int key){
        int index = 0;
        for(; index < data.length; index ++){
            if(data[index] != null && data[index].key == key){
                break;
            }
        }
        return index == data.length ? -1 : index;
    }

}

查询O(1)版

class LRUCache {
    int size;
    int capacity;

    Entry head;
    Entry tail;
    Map<Integer,Entry> index;

    private static class Entry{
        int key;
        int value;

        Entry next;
        Entry pre;
    }


    public LRUCache(int capacity) {
        if(capacity < 0){
            throw new IllegalStateException();
        }
        this.capacity = capacity + 1;
        size = 0;
        head = new Entry();
        tail = new Entry();
        head.next = tail;
        tail.pre = head;
        index = new HashMap<>();

    }
    
    public int get(int key) {
        Entry e = getEntry(key);
        return e == null ? -1 : e.value;
    }

    private Entry getEntry(int key){
        Entry e = index.get(key);
        if(e != null){
            Entry preNode = e.pre;
            Entry nextNode = e.next;
            preNode.next = nextNode;
            nextNode.pre = preNode;
            Entry first = head.next;
            head.next = e;
            e.next = first;
            first.pre = e;
        }
        return e;
    }


    public void put(int key, int value) {
         Entry e = getEntry(key);
         if(e == null){
             e = new Entry();
             e.key = key;
             e.value = value;
             Entry first = head.next;
             head.next = e;
             e.pre = head;
             e.next = first;
             first.pre = e;

             size ++;
             index.put(key,e);

             fixAfterInsert();
         }else{
             e.value = value;
         }
    }

    private void fixAfterInsert(){
        if(tail.pre == head){
            return;
        }
        if(size > capacity){
            Entry drop = tail.pre;
            Entry preNode = drop.pre;
            preNode.next = tail;
            tail.pre = preNode;
            drop.pre = null;
            drop.next = null;
            index.remove(drop.key);
            size --;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354

推荐阅读更多精彩内容