zoukankan      html  css  js  c++  java
  • Leetcode146-lru-cache

    Leetcode146-lru-cache

      int capacity;
        int size;
        Map<Integer, ListNode> map = new HashMap<Integer, ListNode>();
        ListNode head;
        ListNode last;
    
        class ListNode {
            int key;
            int value;
            ListNode prev;
            ListNode next;
    
            public ListNode(int key, int val) {
                this.key = key;
                this.value = val;
                prev = null;
                next = null;
            }
    
            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 LRUCache(int capacity) {
            this.capacity = capacity;
        }
    
        public int get(int key) {
    
            if (map.containsKey(key)) {
                return key;
            }
            return -1;
        }
    
        public void put(int key, int value) {
    
            if (map.containsKey(key)) {
    
               moveNode(key, value);
    
            } else {
    
                if (size < capacity) {
                    insertNode(key, value);
                    size++;
                } else {
                    insertNode(key, value);
                    last = last.next;
                }
            }
        }
    
        public void insertNode(int key, int value) {
            ListNode node;
            node = new ListNode(key, value);
            node.next = head;
            head = node;
            ListNode current = last;
            while (current.next != null) {
                current = current.next;
            }
            current.next = node;
        }
    
        public void moveNode(int key, int value) {
            ListNode node;
            node = new ListNode(key, value);
            node.next = head;
            head = node;
            while (node.next.getKey() != key && node.next.getKey() != last.getKey()) {
                node = node.next;
            }
            node.next = node.next.next;
            ListNode current = last;
            while (current.next.getKey() != key && current.next.getKey() != last.getKey()) {
                current = current.next;
            }
            current.next = current.next.next;
        }
    

      

  • 相关阅读:
    mybatis-cache model
    多线程开发(1)
    正则表达式(3) — 正则表达式库
    正则表达式(2) — 表达式规则
    我在迈瑞工作的两年总结
    正则表达式(1) — 常用的表达式
    C++系列(2) — 智能指针
    C++系列(1) — string
    路径去除前缀
    SIMD性能优化
  • 原文地址:https://www.cnblogs.com/Jomini/p/11997803.html
Copyright © 2011-2022 走看看