题解 | 设计LRU缓存结构

设计LRU缓存结构

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

import java.util.*;


public class Solution {
    int size;
    ArrayList<Entry> list =  new ArrayList<Entry>();
    public Solution(int capacity) {
// write code here
        this.size = capacity;
    }

    public int get(int key) {
// write code here
        int index=0;
        Entry entry=null;
        boolean exist=false;
        for (int i=0;i<list.size();i++) {
            if (list.get(i).key == key) {
                index=i;
                exist=true;
                break;
            }
        }
        if(exist){
        entry=list.get(index);
        list.remove(index);
        list.add(entry);
        return entry.value;
        }
        return -1;
    }

    public void set(int key, int value) {
// write code here
        boolean exist=false;
        for (Entry entry : list) {
            if (entry.key == key) {
                 entry.value=value;
                 exist=true;
            }
        }
        if(!exist){
          list.add(new Entry(key,value));
          if(list.size()>size){
            list.remove(0);
          }
        }
    }

    static class Entry {
        int key;
        int value;
        public Entry(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
}

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

用数组实现;数组的0号索引为最不经常使用的元素,每次访问完一个元素把该元素先从数组中删除再加入数组尾部;

全部评论

相关推荐

09-18 20:41
门头沟学院 Java
要个offer怎么这...:哈哈哈哈哈哈,我也拿了0x10000000个offer,秋招温啦啦啦,好开心
我的秋招日记
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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