【Leetcode】155. 最小栈

155. 最小栈

题目: 155. 最小栈

题解:

 1 class MinStack {
 2 public:
 3     MinStack() {
 4         getmin = INT_MAX;
 5     }
 6     
 7     void push(int val) {
 8         st.push(val);
 9         getmin = min(getmin, val);
10     }
11     
12     void pop() {
13         if(st.top() == getmin)
14         {
15             st.pop();
16             getmin = INT_MAX;
17             stack<int> temp;
18             while(!st.empty())
19             {
20                 temp.push(st.top());
21                 getmin = min(getmin, st.top());
22                 st.pop();
23             }
24             while(!temp.empty())
25             {
26                 st.push(temp.top());
27                 temp.pop();
28             }
29         }
30         else
31             st.pop();
32     }
33     
34     int top() {
35         return st.top();
36     }
37     
38     int getMin() {
39         return getmin;
40 
41     }
42     int getmin;
43     stack<int> st;
44 };
45 
46 /**
47  * Your MinStack object will be instantiated and called as such:
48  * MinStack* obj = new MinStack();
49  * obj->push(val);
50  * obj->pop();
51  * int param_3 = obj->top();
52  * int param_4 = obj->getMin();
53  */

 

上一篇:M3U8工具下载视频教程


下一篇:Leetcode 56-合并区间