首页 > 其他 > 详细

剑指 Offer 30. 包含min函数的栈

时间:2020-08-10 22:34:13      阅读:95      评论:0      收藏:0      [点我收藏+]
public class MinStack {
    /** initialize your data structure here. */
    Stack<Integer> stack = new Stack<>();
    private int min = Integer.MIN_VALUE;
    List<Integer> list = new ArrayList<>();

    public MinStack() {

    }

    public void push(int x) {
        stack.push(x);
        if(list.isEmpty()){
            list.add(x);
            min = x;
        }else{
            if(list.get(0) >= x){
                list.add(0,x);
                min = x;
            }else{
                int i = 1;
                while (i<list.size() && list.get(i) < x){
                    i++;
                }
                if(i == list.size()){
                    list.add(x);
                }else{
                    list.add(i,x);
                }
            }
        }
    }

    public void pop() {
        int pop = stack.pop();
        for(int i = 0;i<=list.size();i++){
            if(list.get(i) == pop){
                list.remove(i);
                if(i == 0) {
                    if(list.isEmpty()){
                        min = Integer.MIN_VALUE;
                    }else {
                        min = list.get(0);
                    }
                }
                break;
            }
        }
    }

    public int top() {
        return stack.peek();
    }

    public int min() {
        return min;
    }

技术分享图片

 

 


方法二:

class MinStack {

    /** initialize your data structure here. */
    Stack<Integer> stack = new Stack<>();
    Stack<Integer> stack_temp = new Stack<>();

    public MinStack() {

    }

    public void push(int x) {
        stack.push(x);
        if(stack_temp.isEmpty()){
            stack_temp.add(x);
        }else{
            if(stack_temp.peek() >= x){
                stack_temp.push(x);
            }else{
                stack_temp.push(stack_temp.peek());
            }
        }
    }

    public void pop() {
        stack.pop();
        stack_temp.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int min() {
        if(stack_temp.isEmpty()){
            return Integer.MIN_VALUE;
        }else{
            return stack_temp.peek();
        }
    }
}

技术分享图片

 

剑指 Offer 30. 包含min函数的栈

原文:https://www.cnblogs.com/taoyuxin/p/13472421.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!