鱼C论坛

 找回密码
 立即注册
查看: 2359|回复: 0

[学习笔记] leetcode 155. Min Stack

[复制链接]
发表于 2019-9-2 05:16:38 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

  2. push(x) -- Push element x onto stack.
  3. pop() -- Removes the element on top of the stack.
  4. top() -- Get the top element.
  5. getMin() -- Retrieve the minimum element in the stack.


  6. Example:

  7. MinStack minStack = new MinStack();
  8. minStack.push(-2);
  9. minStack.push(0);
  10. minStack.push(-3);
  11. minStack.getMin();   --> Returns -3.
  12. minStack.pop();
  13. minStack.top();      --> Returns 0.
  14. minStack.getMin();   --> Returns -2.
复制代码

  1. class MinStack {

  2.     static int min = 2147483647;
  3.     static int top = 0;
  4.     static int[] array;
  5.    
  6.     public MinStack() {
  7.         
  8.         min = 2147483647;
  9.         top =0;
  10.         array = new int[10000];
  11.         
  12.     }
  13.    
  14.     public void push(int x) {
  15.         
  16.         if(x < min) min = x;
  17.         array[top++] = x;
  18.         
  19.     }
  20.    
  21.     public void pop() {
  22.         
  23.         if(top() == min) getNewMin();
  24.         
  25.         top--;
  26.         
  27.     }
  28.    
  29.     public int top() {
  30.         
  31.         return array[top-1];
  32.         
  33.     }
  34.    
  35.     public int getMin() {
  36.         
  37.         return min;
  38.         
  39.     }
  40.    
  41.     public void getNewMin(){
  42.         
  43.         min = 2147483647;
  44.         
  45.         for(int i = 0; i< top-1; i++){
  46.             
  47.             if(array[i] < min) min = array[i];
  48.         }
  49.     }
  50. }

  51. /**
  52. * Your MinStack object will be instantiated and called as such:
  53. * MinStack obj = new MinStack();
  54. * obj.push(x);
  55. * obj.pop();
  56. * int param_3 = obj.top();
  57. * int param_4 = obj.getMin();
  58. */
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-13 18:06

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表