zoukankan      html  css  js  c++  java
  • 最小栈

    设计一个支持 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();
     */
  • 相关阅读:
    jvm的那些设置参数你都知道吗
    进程之间究竟有哪些通信方式
    从零开始带你成为JVM实战高手
    java 面试题目(java高级架构)
    面试要点补充
    Paxos算法与Zookeeper分析,zab (zk)raft协议(etcd) 8. 与Galera及MySQL Group replication的比较
    一文搞懂Raft算法
    Python 循环语句
    Python 条件语句
    Python 运算符
  • 原文地址:https://www.cnblogs.com/yihangZhou/p/9929397.html
Copyright © 2011-2022 走看看