• 155--MinStack


    /*
        解法一:使用链表从0实现栈,用min来存放最小值。
                复杂的地方是,如果pop了最小的数,就要遍重新找到最小的数。
     */
    public class MinStack {
        List<Integer> list;
        int min;
        /** initialize your data structure here. */
        public MinStack() {
            list=new LinkedList<>();
            min=Integer.MAX_VALUE;
        }
    
        public void push(int x) {
            if (x<min)
                min=x;
            list.add(x);
        }
    
        public void pop() {
            if (min==list.get(list.size()-1)){
                min=Integer.MAX_VALUE;
                for (int i=0;i<list.size()-1;i++){
                    if (list.get(i)<min)
                        min=list.get(i);
                }
            }
            if (list.size()!=0)
                list.remove(list.size()-1);
    
        }
    
        public int top() {
            return list.get(list.size()-1);
        }
    
        public int getMin() {
            return min;
        }
        /*
            解法二:使用Java的栈,并用一个辅助栈来存最小值。
         */
        public class MinStack2{
            Stack<Integer> stack;
            Stack<Integer> helper;
            /** initialize your data structure here. */
            public MinStack2() {
                stack=new Stack<>();
                helper=new Stack<>();
            }
    
            public void push(int x) {
                stack.push(x);
                if (helper.isEmpty()||x<=helper.peek())
                    helper.push(x);
            }
    
            public void pop() {
                if (!stack.isEmpty()){
                    int i=stack.pop();
                    if (i==helper.peek())
                        helper.pop();
                }
            }
    
            public int top() {
                if (!stack.isEmpty())
                    return stack.peek();
                throw new RuntimeException("stack is empty");
            }
    
            public int getMin() {
                if (!helper.isEmpty())
                    return helper.peek();
                throw new RuntimeException("stack is empty");
            }
        }
    
    }
  • 相关阅读:
    Vue
    多线程
    多进程进阶
    CentOS7中安装MySQL
    socket
    回顾
    Hibernate学习一:Hebinate入门以及一些小问题
    struts2学习二:Tomcat的部署目录和访问路径问题
    struts2学习一:hello struts2及struts2环境配置中遇到的问题
    Scanner几个问题与正则简介
  • 原文地址:https://www.cnblogs.com/zhangyuhao/p/11548761.html
Copyright © 2020-2023  润新知