【23】155. Min Stack
155. Min Stack
- Total Accepted: 110976
- Total Submissions: 417000
- Difficulty: Easy
- Contributors: Admin
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.
Example:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> Returns -3. minStack.pop(); minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2.
1 class MinStack { 2 public: 3 /** initialize your data structure here. */ 4 MinStack() { 5 6 } 7 8 void push(int x) { 9 s1.push(x); 10 if(s2.empty() || s2.top() >= x) s2.push(x);//要大于等于!重复值要存! 11 } 12 13 void pop() { 14 if(s2.top() == s1.top() && !s2.empty()) s2.pop(); 15 s1.pop(); 16 } 17 18 int top() { 19 return s1.top(); 20 } 21 22 int getMin() { 23 return s2.top(); 24 } 25 26 private: 27 stack<int> s1, s2; 28 }; 29 30 /** 31 * Your MinStack object will be instantiated and called as such: 32 * MinStack obj = new MinStack(); 33 * obj.push(x); 34 * obj.pop(); 35 * int param_3 = obj.top(); 36 * int param_4 = obj.getMin(); 37 */