155. 最小栈

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

  • push(x) -- 将元素 x 推入栈中。
  • pop() -- 删除栈顶的元素。
  • top() -- 获取栈顶元素。
  • getMin() -- 检索栈中的最小元素。

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.


 1 class MinStack {
 2 public:
 3     /** initialize your data structure here. */
 4     std::stack<int> stack1,stack2;
 5     MinStack() {
 6         
 7     }
 8     
 9     void push(int x) {
10         stack1.push(x);
11         if(stack2.empty())
12             stack2.push(x);
13         else if( x  <= stack2.top())
14             stack2.push(x);
15     }
16     
17     void pop() {
18         int num1;
19         // write your code here
20         if(stack1.top()==stack2.top())
21         {  
22             stack1.pop(); 
23             num1 =  stack2.top();
24             stack2.pop();
25         }else {
26            num1 = stack1.top();
27            stack1.pop();
28         }
29        
30     }
31     
32     int top() {
33         int num = stack1.top();
34         return  num;
35     }
36     
37     int getMin() {
38         int num = stack2.top();
39         return  num;
40     }
41 };
42 
43 /**
44  * Your MinStack object will be instantiated and called as such:
45  * MinStack obj = new MinStack();
46  * obj.push(x);
47  * obj.pop();
48  * int param_3 = obj.top();
49  * int param_4 = obj.getMin();
50  */
原文地址:https://www.cnblogs.com/jj81/p/10068277.html