[Leetcode] 146. LRU Cache

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

Solution:
结合double linkedlist和hashmap
hashmap用于存储并且快速查找
double linkedlist用于快速删除/增加

class LRUCache {
    
    // linkedlist中node的设定
    class Node {
        int key;
        int val;
        Node pre;
        Node next;
        // 给node赋key和value
        public Node(int k, int v) {
            this.key = k;
            this.val = v;
        }
    }
    
    // 利用map快速查找
    Map<Integer, Node> map;
    // 用head和tail两个无用的node,本质上是为了在增删的时候更方便操作
    Node head;
    Node tail;
    int size;
    int capacity;
    
    public LRUCache(int capacity) {
        this.capacity = capacity; // 注意写法
        size = 0;
        head = new Node(0,0);
        tail = new Node(0,0);
        // 注意要把head和tail连接起来
        head.next = tail;
        tail.pre = head;
        map = new HashMap<>(); 
    }
    
    // 每当get key的时候,就需要从linkedlist中删除该node并重新在列头插入
    public int get(int key) {
        if(map.containsKey(key)) {
            Node cur = map.get(key);
            remove(key); // remove node from double linkedlist
            addHead(key, cur.val); // no need to touch map cuz key is still there
            return cur.val;
        } else {
            return -1;
        }
    }
    
    // 将key放入的时候,从list原位置删除key, 并在列头插入node
    // 可以在put以后检查size和capacity,当然在addHead方法中检查也可以
    public void put(int key, int value) {
        // Node cur = new Node(key, value);
        if(map.containsKey(key)) {
            remove(key);
            addHead(key, value);
        } else {
            addHead(key, value);
        }
        
        
    }
    
    public void remove(int key) {
        Node cur = map.get(key);
        cur.pre.next = cur.next;
        cur.next.pre = cur.pre;
        size--;
        map.remove(key); // 需要注意remove的时候,map中也要移除key
    }
    
    public void addHead(int key, int value) {
        
        Node cur = new Node(key, value);
        map.put(key, cur);
        
        // 一共四条link
        Node preHead = head.next;
        head.next = cur;
        cur.next = preHead;
        cur.pre = head;
        preHead.pre = cur;
        size++;
        
        // evicts LRU cache
        // 检查size是否溢出
        if(size > capacity) {
            Node node = tail.pre;
            remove(node.key);
        }
    }
}

/**
 * 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);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值