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. Show Tags Have you met this question in a real interview? Yes No
Discuss
ÌâÒ⣺дһ¸öеÄÕ»£ºÖ§³ÖÈëÕ»£¬³öÕ»£¬µÃµ½Õ»¶¥£¬ºÍµÃµ½´Ëʱջ×îСµÄÄǸöÊý
˼·£ºÇ°Èý¸ö²Ù×÷¶¼¿ÉÒÔÓÃÒ»¸öÕ»À´ÊµÏÖ£¬Çó×îСµÄ»°¾ÍÐèÒªÒ»¸öеĵ¥µ÷Õ»À´Î¬»¤ÁË£¬Õâ¸öеĵ¥µ÷Õ»ÐèҪעÒâµÄµØ·½ÊÇ£ºµ±ÔʼµÄÕ»popµôÒ»¸öÊýµÄʱºò¿ÉÄÜ»áÓ°Ïìµ½Õâ¸öµ¥µ÷Õ»£¬Ö»ÒªÅжϴËʱpopµôµÄ»°£¬ÊDz»Êǵ¥µ÷Õ»µÄÕ»¶¥¾ÍÄܽâ¾öÁË£¬ÒòΪÕâ¸öµ¥µ÷Õ»ÊÇÔʼջµÄ×Ó¼¯
class MinStack { public: void push(int x) { st.push(x); if (stm.empty() || stm.top() >= x) stm.push(x); } void pop() { int top = st.top(); st.pop(); if (top == stm.top()) stm.pop(); } int top() { return st.top(); } int getMin() { return stm.top(); } private: stackst; stack stm; };