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

 

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.


设计一个栈,有一个取最小元素的操作

C++(29ms): 用两个栈
 1 class MinStack {
 2 private:
 3     stack<int> s1 ;
 4     stack<int> s2 ;
 5 public:
 6     void push(int x) {
 7         s1.push(x) ;
 8         if (s2.empty() || x <= getMin())
 9             s2.push(x) ;
10     }
11     
12     void pop() {
13         if (s1.top() == getMin())
14             s2.pop() ;
15         s1.pop() ;
16     }
17     
18     int top() {
19         return s1.top() ;
20     }
21     
22     int getMin() {
23         return s2.top() ;
24     }
25 };
26 
27 /**
28  * Your MinStack object will be instantiated and called as such:
29  * MinStack obj = new MinStack();
30  * obj.push(x);
31  * obj.pop();
32  * int param_3 = obj.top();
33  * int param_4 = obj.getMin();
34  */

 


C++(29ms): 一个栈 注意用long
 1 class MinStack {
 2 private:
 3     stack<long> s ;
 4     
 5     long Min ;
 6 public:
 7     void push(int x) {
 8         if (s.empty()){
 9             s.push(0) ;
10             Min = x ;
11         }else{
12             s.push(x-Min) ;
13             if (x < Min)
14                 Min = x ;
15         }
16     }
17     
18     void pop() {
19         if (s.empty())
20             return ;
21         long top = s.top() ;
22         if (top < 0)
23             Min -= top ;
24         s.pop() ;
25     }
26     
27     int top() {
28         long top = s.top() ;
29         if (top > 0){
30             return (int)top+Min ;
31         }else{
32             return (int)Min ;
33         }
34     }
35     
36     int getMin() {
37         return (int)Min ;
38     }
39 };
40 
41 /**
42  * Your MinStack object will be instantiated and called as such:
43  * MinStack obj = new MinStack();
44  * obj.push(x);
45  * obj.pop();
46  * int param_3 = obj.top();
47  * int param_4 = obj.getMin();
48  */

 

 
posted @ 2018-03-19 14:54  __Meng  阅读(116)  评论(0编辑  收藏  举报