1 class MinStack { 2 public: 3 void push(int x) { 4 if(values.empty()) 5 { 6 values.push_back(x); 7 min_indices.push_back(0); 8 } 9 else 10 { 11 if( x < values[min_indices.back()] ) 12 min_indices.push_back(values.size()); 13 values.push_back(x); 14 } 15 16 } 17 18 void pop() { 19 values.pop_back(); 20 if(values.size() == min_indices.back()) 21 min_indices.pop_back(); 22 } 23 24 int top() { 25 return values.back(); 26 } 27 28 int getMin() { 29 return values[min_indices.back()]; 30 } 31 private: 32 deque<int> values; 33 deque<deque<int>::size_type> min_indices; 34 };
using the std::vector will lead to ‘memory limit exceeded’, so i use the deque instead.
时间: 2024-11-10 11:33:40