161.Min Stack

题目:

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

设计一个支持push,pop,top和在恒定时间内检索最小元素的堆栈。

  • 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.

Example:

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.

解答:

 1 class MinStack {
 2     
 3     private int min;   //存储最小值
 4     private Stack<Integer> stack;  //按入栈顺序存储除了最小值外的元素,注意并没有按大小顺序存储(可能会有最小值插入正常顺序中)
 5 
 6     /** initialize your data structure here. */
 7     public MinStack() {
 8         min=Integer.MAX_VALUE;
 9         stack=new Stack<>();
10     }
11     
12     public void push(int x) {
13         if(x<=min){           //x比当前最小值小
14             stack.push(min);  //先把当前最小值入栈
15             min=x;            //将最小值赋值为x
16         }
17         stack.push(x);        //x无论大小与否,都入栈
18     }
19     
20     public void pop() {
21         if(stack.pop()==min)  //如果当前栈顶元素为min,弹出后
22             min=stack.pop();  //将新栈顶元素(前最小值)弹出赋值给min
23     }
24     
25     public int top() {
26         return stack.peek();
27     }
28     
29     public int getMin() {
30         return min;
31     }
32 }
33 
34 /**
35  * Your MinStack object will be instantiated and called as such:
36  * MinStack obj = new MinStack();
37  * obj.push(x);
38  * obj.pop();
39  * int param_3 = obj.top();
40  * int param_4 = obj.getMin();
41  */

详解:

一旦有最小值出现,就把之前的最小值入栈,再把当前值(也是当前最小值)入栈

这样出栈时,一旦弹出的是最小值,就把第二小的值继续出栈赋值给min

猜你喜欢

转载自www.cnblogs.com/chanaichao/p/9632783.html