设计getMin功能的栈

设计getMin功能的栈

https://www.nowcoder.com/practice/c623426af02d4c189f92f2a99647bd34?tpId=117&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fjob-code-high%2Fquestion-ranking&tab=answerKey

 public int[] getMinStack (int[][] op) {
        // write code here
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<op.length;i++){
            if(op[i][0]==3){
                list.add(stack2.peek());
            }else if(op[i][0]==2){
                int a = stack1.pop();
                if(a==stack2.peek()) stack2.pop();
            }else{
                int temp = op[i][1];
                stack1.push(temp);
                //这里注意判断stack2是否为空
                if(stack2.isEmpty() || temp<=stack2.peek()) stack2.push(temp);
            }
        }
        int[] res = new int[list.size()];
        for(int i=0;i<list.size();i++){
            res[i] = list.get(i);
        }
        return res;
    }
全部评论

相关推荐

28小凳也想实习:项目不用一个业务一个轮子吗,刷牛客好多人说要一业务一轮子
点赞 评论 收藏
分享
黑皮白袜臭脚体育生:简历条例统一按使用了什么技术实现了什么功能解决了问题或提升了什么性能指标来写会好些,如使用布隆过滤器实现了判断短链接是否存在,大大提升了查询速度
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务