题解 | #设计LRU缓存结构#

设计LRU缓存结构

https://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84

import java.util.*;


public class Solution {
    class node {
        int key;
        int value;
        public node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
    List<node> list=new LinkedList<>();
    public int capacity;

    public Solution(int capacity) {
        // write code here
        
        this.capacity = capacity;
    }

    public int get(int key) {
        
        for (node n : list) {
            if (n.key == key) {
                list.remove(n);
                list.add(n);
                return n.value;
            }
        }
        
        return -1;
    }

    public void set(int key, int value) {
        // write code here
        if(list.size()<this.capacity){
            node n=new node(key,value);
            int index=contains(n.key);
            if(index<0){
                list.add(n);
                
            }else{
                list.set(index,n);
                list.remove(n);
                list.add(n);
                
            } 
        }else{
            list.remove(0);
            node n=new node(key,value);
            list.add(n);
        }
    }
    public int contains(int key){
        int i=0;
        for (node n : list) {
            if (n.value == key) {
                return i;
            }
            i++;
        }
        return -1;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution solution = new Solution(capacity);
 * int output = solution.get(key);
 * solution.set(key,value);
 */

全部评论

相关推荐

大疆在线测评都考什么呀,会考企业概况啥的吗
又被画饼了的做题家很...:不会。刚做完,就是材料分析、态度题、算术题、逻辑题。总共60道。
投递大疆等公司7个岗位
点赞 评论 收藏
分享
下北澤大天使:你是我见过最美的牛客女孩😍
点赞 评论 收藏
分享
05-26 22:25
门头沟学院 Java
Java小肖:不会是想叫你过去把你打一顿吧,哈哈哈
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务