https://leetcode.com/problems/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.

思路:

关键在于找最小值要O(1)复杂度,所以空间换时间。一个额外的vector存储递减序入栈的数字。

AC代码:

 1 class MinStack {
 2 public:
 3     MinStack(){ st_min.push_back(INT_MAX); };
 4     void push(int x) {
 5         if (x <= st_min[st_min.size()-1])
 6             st_min.push_back(x);
 7         st.push_back(x);
 8         return;
 9     }
10 
11     void pop() {
12         if (st[st.size() - 1] == st_min[st_min.size() - 1]){
13             st_min.pop_back();
14         }
15         st.pop_back();
16         return;
17     }
18 
19     int top() {
20         return st[st.size() - 1];
21     }
22 
23     int getMin() {
24         return st_min[st_min.size() - 1];
25     }
26 
27 private:
28     vector<int> st;
29     vector<int> st_min;
30 };