栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

牛客网:NC93 设计LRU缓存结构

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

牛客网:NC93 设计LRU缓存结构

package com.company.test.设计LRU缓存结构;

import java.util.*;



public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution(2);
       
        solution.set(1,1);
        solution.set(2,2);
        solution.set(1,2);
        solution.set(3,3);
        System.out.println(solution.get(1));
    }

    Map cache;
    int size;
    int capacity;
    Node head;
    Node tail;

    public Solution(int capacity) {
        // write code here
        cache = new HashMap<>();
        size = 0;
        this.capacity = capacity;
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.pre = head;
    }

    private void remove(Node node){
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }


    private void addHade(Node node){
        node.pre = head;
        node.next = head.next;
        head.next.pre = node;
        head.next = node;
    }

    private void moveToHead(Node node){
        remove(node);
        addHade(node);
    }

    private Node deletetail(){
        Node tail = this.tail.pre;
        remove(tail);
        return tail;
    }

    public int get(int key) {
        // write code here
        Node node = cache.get(key);
        if (node == null){
            return -1;
        }
        moveToHead(node);
        return node.value;
    }

    public void set(int key, int value) {
        // write code here
        Node node = cache.get(key);
        if (node == null){
            Node newNode = new Node(key, value);
            cache.put(key, newNode);
            addHade(newNode);
            size++;
            if (size > capacity){
                Node tail = deletetail();
                cache.remove(tail.key);
                size--;
            }
        } else{
            cache.get(key).value = value;
            moveToHead(node);
        }

    }


    class Node {
        int key;
        int value;
        Node pre;
        Node next;

        public Node (){};

        public Node (int key, int value){
            this.key = key;
            this.value = value;
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1021257.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号