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

设计LRU缓存结构

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

import java.util.*;


public class Solution {

     HashMap<Integer,MyNode> map;
     int size;
     MyNode begin = new MyNode(-1);
     MyNode end = new MyNode(-1);
    public Solution(int capacity) {
        // write code here
        map = new HashMap<Integer,MyNode>();
        size = capacity;
        begin.next = end;
        end.last = begin;
    }

    public int get(int key) {
        // write code here
        if(map.containsKey(key)){
             MyNode temp = map.get(key);
             temp.next.last = temp.last;
             temp.last.next = temp.next;
             temp.last = end.last;
             end.last.next = temp;
             end.last = temp;
             temp.next = end;
             return temp.val;
        }
        return -1;
    }

    public void set(int key, int value) {
        // write code here
        if(map.containsKey(key)){
             MyNode one = map.get(key);
             one.val = value;
             one.last.next = one.next;
             one.next.last = one.last;
             one.last = end.last;
             end.last.next = one;
             end.last = one;
             one.next = end;
        }else{
             if(map.size() < size){
             MyNode one = new MyNode(value,key,end,end.last);
             map.put(key,one);
             one.last = end.last;
             end.last.next = one;
             end.last = one;
             one.next = end;
          }else{
             MyNode one = new MyNode(value,key,end,end.last);
             map.put(key,one);
             one.last = end.last;
             end.last.next = one;
             end.last = one;
             one.next = end;
             MyNode two = map.remove(begin.next.key);
             begin.next = two.next;
             two.next.last = begin;
          }
        }
    }
    class MyNode{
         MyNode next;
         MyNode last;
         int key;
         int val;
         public MyNode(int val){
              this.val = val;
         }
         public MyNode(int val,int key){
              this.val = val;
              this.key = key;
         }
         public MyNode(int val,int key , MyNode next,MyNode last){
              this.val = val;
              this.key = key;
              this.next = next;
              this.last = last;
         }
    }
}

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

相关推荐

02-15 17:05
已编辑
东华理工大学 前端工程师
Beeee0927:我建议是精简一点吧,比如主修的课程,技能特长,自我评价我是觉得可以删掉了。然后项目经历可能要考虑怎么改得更真实一点,因为就我看起来感觉里面太多的东西像是在实际项目中才能接触到的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务