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.
1 class MinStack { 2 private: 3 stack<int> stk; 4 stack<int> minstack; 5 public: 6 void push(int x) { 7 stk.push(x); 8 if(minstack.empty()) 9 { 10 minstack.push(x); 11 }else 12 { 13 if(x<=minstack.top()) 14 minstack.push(x); 15 } 16 } 17 18 void pop() { 19 if(stk.top()==minstack.top()) 20 { 21 stk.pop(); 22 minstack.pop(); 23 }else 24 { 25 stk.pop(); 26 } 27 } 28 29 int top() { 30 return stk.top(); 31 } 32 33 int getMin() { 34 return minstack.top(); 35 } 36 };
时间: 2024-12-15 06:16:04