zoukankan      html  css  js  c++  java
  • 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.

     https://leetcode.com/problems/min-stack/

     1 import java.util.ArrayList;
     2 import java.util.List;
     3 
     4 class MinStack
     5 {
     6     static class Element
     7     {
     8         final int value;
     9         final int min;
    10         Element(final int value, final int min)
    11         {
    12             this.value = value;
    13             this.min = min;
    14         }
    15     }
    16     private List<Element> list=new ArrayList();
    17     public void push(int x) 
    18     {
    19         if(list.isEmpty())
    20             list.add(new Element(x,x));
    21         else
    22             list.add(new Element(x,Math.min(x,list.get(list.size()-1).min)));
    23     }
    24 
    25     public void pop() 
    26     {
    27         list.remove(list.size()-1);//
    28     }
    29 
    30     public int top() 
    31     {
    32         return list.get(list.size()-1).value;
    33     }
    34 
    35     public int getMin() 
    36     {
    37         return list.get(list.size()-1).min;
    38     }
    39 }
     1 public class test
     2 {
     3     public static void main(String[] args)
     4     {
     5         MinStack st=new MinStack();
     6         st.push(5);
     7         st.push(6);
     8 //        st.pop();
     9         int t=st.top();
    10         st.push(1);
    11         st.push(2);
    12         st.push(3);
    13         st.push(4);
    14         int m=st.getMin();
    15     }
    16 }
  • 相关阅读:
    初探 Linux
    操作系统简介
    1208. 尽可能使字符串相等
    643. 子数组最大平均数 I
    480. 滑动窗口中位数
    Bisect in Python
    HTTP 和 HTTPS 的区别
    URI和URL的区别
    HTTP 1.0和HTTP 1.1的主要区别是什么?
    MySQL游标的使用笔记大全
  • 原文地址:https://www.cnblogs.com/qq1029579233/p/4404408.html
Copyright © 2011-2022 走看看