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


    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();
            }
        }
    }

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    挖矿程序linux 删除
    本地复制vue项目
    新建vue项目
    CentOS7单用户模式
    CentOS6
    CentOS6-系统管理操作
    CentOS7-系统管理操作
    VMWare克隆虚拟机
    虚拟机网络模式设置为NAT
    VI/VIM编辑器
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/13472421.html
Copyright © 2020-2023  润新知