zoukankan      html  css  js  c++  java
  • [leetcode]155. Min Stack最小栈

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

    • push(x) -- Push element x onto stack.
    • pop() -- Removes the element on top of the stack.
    • top() -- Get the top element.
    • getMin() -- Retrieve the minimum element in the stack.
    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.getMin();   --> Returns -3.
    minStack.pop();
    minStack.top();      --> Returns 0.
    minStack.getMin();   --> Returns -2.

    题意:

    请设计一个栈结构,支持 push、pop、top以及getMin操作,且每个操作的时间复杂度都是 O(1)。

    思路:

    维护一个单调栈minStack

    code

     1 class MinStack {
     2 
     3     /** initialize your data structure here. */
     4     Stack<Integer> s ;
     5     Stack<Integer> minStack ;
     6     
     7     public MinStack() {
     8             s = new Stack<>();
     9             minStack = new Stack<>();
    10     }
    11     
    12     public void push(int x) {
    13         s.push(x);
    14         int minValue = minStack.isEmpty() ? x: Math.min(minStack.peek(), x);
    15         minStack.push(minValue);
    16         
    17     }
    18     
    19     public void pop() {
    20         s.pop();
    21         minStack.pop();
    22     }
    23     
    24     public int top() {
    25         return s.peek();
    26         
    27         
    28     }
    29     
    30     public int getMin() {
    31         return minStack.peek();
    32     }
    33 }
  • 相关阅读:
    windows 根据端口查看进行PID 并杀掉进程
    Linux下安装mysql-5.7
    springcloud参考视频和源码笔记
    idea中配置热部署
    技术/方案实现目录
    系统功能设计产出模版
    JQuery点击行tr实现checkBox选中与未选中切换
    Java学习第一天
    ES6 记录
    微信小程序记录
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10873295.html
Copyright © 2011-2022 走看看