• 最小栈


    设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

    • push(x) -- 将元素 x 推入栈中。
    • pop() -- 删除栈顶的元素。
    • top() -- 获取栈顶元素。
    • getMin() -- 检索栈中的最小元素。

    示例:

    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.getMin();   --> 返回 -3.
    minStack.pop();
    minStack.top();      --> 返回 0.
    minStack.getMin();   --> 返回 -2.

    class MinStack {
        ArrayList<Integer> list=new ArrayList<>();   
       
        /** initialize your data structure here. */
        public MinStack() {       
        }
       
        public void push(int x) {
            list.add(x);
           
        }
       
        public void pop() {
            list.remove(list.size()-1);
           
        }
       
        public int top() {
            return list.get(list.size()-1);
        }
       
        public int getMin() {
            int temp=list.get(list.size()-1);
            for(int i=list.size()-1;i>=0;i--)
            {
                if(temp>list.get(i))temp=list.get(i);
            }
            return temp;
        }
    }
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(x);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.getMin();
     */
  • 相关阅读:
    Geometry
    后缀数组dc3算法模版(待补)
    CodeForces 467D(267Div2-D)Fedor and Essay (排序+dfs)
    HDU 3572 Task Schedule (最大流)
    Acdream手速赛7
    hdu2732 Leapin' Lizards (网络流dinic)
    HDU 3549 Flow Problem (最大流ISAP)
    HDU 1532 Drainage Ditches (网络流)
    [容易]合并排序数组 II
    [容易]搜索插入位置
  • 原文地址:https://www.cnblogs.com/yihangZhou/p/9929397.html
Copyright © 2020-2023  润新知