题解 | #设计LRU缓存结构#

设计LRU缓存结构

http://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61

java版 LRU 使用hash表和双向链表可以使get和put的时间复杂度都是O(1)
1.put操作:判断缓存是否存在,存在:将hash表的数据进行覆盖,将该链表添加到链表头部;不存在:判断缓存容量是否已满,已满:删除链表尾部节点和hash表内容,最后将新的节点插入到链表头部和添加到hash表中
2:get操作:hash表有则将该节点添加到链表头部,并返回value,没有则返回-1;

import java.util.*;


public class Solution {
    /**
     * lru design
     * @param operators int整型二维数组 the ops
     * @param k int整型 the k
     * @return int整型一维数组
     */
    Map<Integer,Node> map = new HashMap();
    DoubleLinkedList linkedList = new DoubleLinkedList();
    public int[] LRU (int[][] operators, int k) {
        // write code here
        List<Integer> list = new ArrayList<>();
        for(int i = 0;i < operators.length;i++){
            int key =  operators[i][1];
            if(operators[i][0] == 1){
                int val = operators[i][2];
                 Node node = new Node(key,val);
                if(map.containsKey(key)){
                    linkedList.delete(map.get(key));
                    map.put(key,node);
                    linkedList.addFirst(node);

                }else{
                    if(map.size() == k){
                        int k1 = linkedList.deleteTail();
                        map.remove(k1); 
                    }
                    linkedList.addFirst(node);
                    map.put(key,node);
                }

            }else{            
                if(map.containsKey(key)){
                    Node no = map.get(key);
                    list.add(no.val);
                    linkedList.delete(no);
                    linkedList.addFirst(no);

                }else{
                    list.add(-1);
                }
            }
        }
        int[] res = new int[list.size()];
        for(int i = 0;i < list.size();i++){
            res[i] = list.get(i);
        }
        return res;

    }
}
class DoubleLinkedList{
    Node head;
    Node tail;
    DoubleLinkedList(){
        this.head = new Node(0,0);
        this.tail = new Node(0,0);
        head.next = tail;
        tail.pre = head;
    }
    //添加到链表头部
    public void addFirst(Node n){
        n.next = head.next;
        n.pre = head;
        head.next.pre = n;
        head.next = n;

    }
    public int delete(Node n){
        n.pre.next = n.next;
        n.next.pre = n.pre;
        return n.key;
    }

    public int deleteTail(){
        if(head == tail){
            return -1;
        }
        return delete(tail.pre);
    }

}
class Node{
    int key;
    int val;
    Node pre;
    Node next;
    Node(int k,int v){
        this.key = k;
        this.val = v;
    }

}
全部评论

相关推荐

01-17 08:34
门头沟学院 Java
想找对象的单身狗在努力存钱:这工资不低了,再高点人家要招博士硕士的
点赞 评论 收藏
分享
02-10 12:23
已编辑
新余学院 C++
采集想要offer:专业技能那里要一条一条的列出来吧,感觉你项目很厉害了,但是如果你不写技术栈面试官对你项目不太懂的话都没办法问你八股😂C++都是基架岗,都是一群9✌🏻在卷,我觉得你要是有时间学个go把MySQL和redis写上去找个开发岗吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务