题解 | #设计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);
 */
全部评论

相关推荐

头像
11-27 17:08
已编辑
牛客_产品运营部_私域运营
腾讯 普通offer 24k~26k * 15,年包在36w~39w左右。
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务