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

    此博客链接:

    题目链接:https://leetcode-cn.com/problems/min-stack/submissions/

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

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

    示例:

    输入:
    ["MinStack","push","push","push","getMin","pop","top","getMin"]
    [[],[-2],[0],[-3],[],[],[],[]]

    输出:
    [null,null,null,null,-3,null,0,-2]

    解释:
    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 {
        //  Stack <Integer> stack=new Starck<>();
         Stack <Integer> stack=new Stack<Integer>();
         int min=Integer.MAX_VALUE;
        /** initialize your data structure here. */
        public MinStack() {
    
        }
        public void push(int x) {
          if(x<=min)
          {
              stack.push(min);
              min=x;
          }
          stack.push(x);
        }
        
        public void pop() {
         if(min==stack.pop())
           min=stack.pop();
        }
        public int top() {
           return stack.peek();
        }
        
        public int getMin() {
          return min;
        }
    }
  • 相关阅读:
    资源与锁
    资源与锁
    Leetcode-Rotate List
    Leetcode-Unique Paths II
    Leetcode-Unique Paths
    Leetcode-Minimum Path Sum
    Leetcode-Sqrt(x)
    Leetcode-Set Matrix Zeroes
    Leetcode-Search a 2D Matrix
    Leetcode-Combinations
  • 原文地址:https://www.cnblogs.com/ping2yingshi/p/13375145.html
Copyright © 2011-2022 走看看