zoukankan      html  css  js  c++  java
  • LRU Cache

    LRU Cache

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

    get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
    set(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.

    思路:

      双向链表

    我的代码:

    public class LRUCache {
        
        public LRUCache(int capacity) {
            this.capacity = capacity;
            this.head = new Node(-1, -1);
            this.tail = new Node(-1, -1);
            head.next = tail;
            tail.pre = head;
        }
        
        public int get(int key) {
            if(!hm.containsKey(key))    return -1;
            Node node = hm.get(key);
            //remove current
            node.pre.next = node.next;
            node.next.pre = node.pre;
            moveTotail(node);
            return node.val;
        }
        
        public void set(int key, int value) {
            if(get(key) != -1)
            {
                hm.get(key).val = value;
                return;
            }
            if(hm.size() == capacity)
            {
                hm.remove(head.next.key);
                head.next = head.next.next;
                head.next.pre = head;
            }
            Node node = new Node(key,value);
            hm.put(key,node);
            moveTotail(node);
        }
        public void moveTotail(Node node){
            node.pre = tail.pre;
            node.next = tail;
            tail.pre.next = node;
            tail.pre = node;
        }
        private Node head; 
        private Node tail;
        private int capacity;
        private HashMap<Integer,Node> hm = new HashMap<Integer,Node>();
        private class Node{
            Node pre;
            Node next;
            int key;
            int val;
            public Node(int key, int val)
            {
                this.key = key;
                this.val = val;
            }
        }
    }
    View Code

    学习之处:

    • 在做这道题的时候,一下子就想到双向链表了,由于自己觉得简单,就边看答案边做的,差评!!!
    • 这道题有点眼高手低,以后不能这样!其实好长时间才AC的
  • 相关阅读:
    tty 与 多任务的解释备忘
    Oracle 安装时候的fs.filemax参数
    100多个Web2.0在线生成器
    精心整理的微软原版光盘
    WEB3.0开启商务魔法时代
    VBO与Displaylists的进一步讨论 (转)
    基于UML和ASP.NET实现三层B/S结构系统开发(转)
    BYTE* To Float*
    COM高手总结的八个经验和教训(转)
    OpenGL: 3D坐标到屏幕坐标的转换逻辑(gluProject的实现)(转)
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4381909.html
Copyright © 2011-2022 走看看