题解 | #设计LRU缓存结构,双栈+hash表#

设计LRU缓存结构

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

import java.util.*;


public class Solution {
    //双栈加,hash表
    //st1栈,栈顶是最近使用的,栈底是最久未使用的
    //st2栈,用来中转数据
    //hash表查询数据
    HashMap<Integer , Integer> map = new HashMap<>() ;
    Stack<Integer> st1 = new Stack<>() ;
    Stack<Integer> st2 = new Stack<>() ;
    int MaxSize = 0 ;
    int size = 0 ;
    public Solution(int capacity) {
        this.MaxSize = capacity ;
    }

    public int get(int key) {
        if(!map.containsKey(key)) return -1 ;
        move(key) ;
        return map.get(key) ;
    }

    public void set(int key, int value) {
        if(map.containsKey(key)) {//已经有,替换,提前
            map.put(key , value) ;
            move(key) ;
        } else {
            if(this.size == this.MaxSize) {//置换,删除栈底的元素
                int last = removeLast() ;
                map.remove((Integer)last) ;
                st1.push(key) ;
                map.put(key , value) ;
            } else {//存储,size++
                map.put(key , value) ;
                this.size ++ ;
                st1.push(key) ;
            }
        }
    }
    //将key移动到栈顶
    public void move(int key) {
        while(!st1.isEmpty()) {
            int cur = st1.pop() ;
            if(cur != key) {
                st2.push(cur) ;
            }
        }
        while(!st2.isEmpty()) {
            st1.push(st2.pop()) ;
        }
        st1.push(key) ;
    }
    //删除栈底,并返回栈底元素
    public int removeLast() {
        int res = 0 ;
        int size = st1.size() ;
        for(int i = 0 ; i < size ; i ++) {
            if(i == size - 1) {
                res = st1.pop() ;
            } else {
                st2.push(st1.pop()) ;
            }
        }
        while(!st2.isEmpty()) {
            st1.push(st2.pop()) ;
        }
        return res ;
    }
}

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

一个菜鸟的算法刷题记录 文章被收录于专栏

分享一个菜鸟的成长记录

全部评论

相关推荐

可爱的牛油果在求佛:我觉得很不错,我通过这份简历,看到的是一个学历不错,经历也有,生活也自律的积极青年,有培养潜力
点赞 评论 收藏
分享
程序员牛肉:小牛肉来也! 基本破不了局了,我给你的建议是适当放弃秋招,投递大厂的日常实习之后赶明年的春招。 在没有实习的情况下,你的项目经历给面试官的作用就是提供提问点方便面试官来提问八股以及场景题而已。因此你现在简历的写法不太对,要着重突出项目中使用的技术点,而不是像你现在这个写的很宽泛。 最好是“基于xxxx技术解决了xxxx问题,解决了xxxx边缘场景问题”。最好是这样写,方便面试官对你的简历进行提问。 最后的最后,问题其实不在你。今年的秋招确实比较寒冬一点,所以找不到是正常的。要做好打持久战的准备。
Java学习交流
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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