[leetcode]LRU Cache-java

注意一下几项

1. 借助linklist动态储存key的使用情况,将每次使用的key对应的节点变化到链表尾部,0位置为最少使用的key

2. 题目对时间复杂度有要求,linklist获得某个key,需要用O(1)的map查找,而是O(n)的循环查找

3. 根据以上两个条件,需要实现map+linklist的数据结构,linklist存储键值和最少用到的key,map根据key找到list对应的节点

 



 

 

public class LRUCache {
    
   private Map<Integer, Node> map;
    private Integer capacity;
    private Node head;
    private Node tail;

    private class Node {
        public Integer key;
        public Node parent;
        public Node next;
        public Integer value;

        private Node(Integer key, Node parent, Node next, Integer value) {
            this.key = key;
            this.parent = parent;
            this.next = next;
            this.value = value;
        }
    }

    public LRUCache(int capacity) {
        this.capacity = capacity;
        map = new HashMap<Integer, Node>(capacity, 1);
        head = new Node(null, null, null, null);
        tail = head;
    }

    public int get(int key) {
        if (!map.containsKey(key)) {
            return -1;
        }
        Node node = map.get(key);
        if(map.size() == 1){
            return node.value;
        }
        node.parent.next = node.next;
        if(node.next !=null){
            node.next.parent = node.parent;
        }else {
            tail = node.parent;
        }
        tail.next = node;
        node.parent = tail;
        tail = node;
        tail.next=null;
        return node.value;
    }

    public void set(int key, int value) {
        Node toDelNode = null;
        if (map.containsKey(key)) {
            toDelNode = map.get(key);
        } else if (map.size() == capacity) {
            toDelNode = head.next;
        }
        if(toDelNode != null){
            toDelNode.parent.next = toDelNode.next;
            if(toDelNode.next != null){
                toDelNode.next.parent = toDelNode.parent;
            }else{
                tail = toDelNode.parent;
            }
            map.remove(toDelNode.key);
            if(map.isEmpty()){
                tail = head;
            }
        }

        if(map.size() < capacity){
            Node node = new Node(key, tail, null, value);
            tail.next = node;
            tail = node;
            tail.next=null;
            map.put(key, node);
        }
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值