码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-08-10 22:08:46      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:min   off   alt   lis   stack   ini   rem   sem   you   

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函数的栈

标签:min   off   alt   lis   stack   ini   rem   sem   you   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!