首页 > 代码库 > Min Stack
Min Stack
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.
1 class MinStack { 2 List<Integer> stack = new ArrayList<Integer>(); 3 int top = -1; 4 int min = Integer.MAX_VALUE; 5 6 public void push(int x) { 7 top++; 8 stack.add(x); 9 if(min > x){10 min = x;11 12 }13 14 }15 16 public void pop() {17 18 int element = stack.remove(top--);19 if(element == min)20 { 21 updateMin(); 22 23 }24 }25 26 public int top() {27 int result = stack.get(top);28 29 return result;30 }31 32 public int getMin() {33 34 return this.min;35 }36 public void updateMin(){37 if(top == -1)38 {39 min = Integer.MAX_VALUE; 40 return;41 }42 min = stack.get(0);43 for(int i = 1; i <= top; i++){44 if(min > stack.get(i))45 min = stack.get(i);46 }47 }48 }
Min Stack
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。