LeetCode 155 Min Stack (minimum Stack)
Translation
The stack design supports pushing, pop, top, and retrieval of the smallest element within the constant time. Push (x) -- push element X into Stack pop () -- Remove top element () -- get top element getMin () -- retrieve the minimum element of stack
Original
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.
Analysis
I have written two questions before, namely, using Stack to implement the Queue function and using Queue to implement the Stack function. It is very easy to use two stacks here.
LeetCode 225 Implement Stack using Queues (Stack implementation using Queue )(*)
LeetCode 232 Implement Queue using Stacks (Queue using Stack )(*)
class MinStack {public: stack
allStack; stack
minSta; void push(int x) { if (allStack.empty()) { allStack.push(x); minSta.push(x); } else { allStack.push(x); if (x <= minSta.top()) minSta.push(x); } } void pop() { if (allStack.top() == minSta.top()) { minSta.pop(); } allStack.pop(); } int top() { return allStack.top(); } int getMin() { return minSta.top(); } };
In addition to the stack above, I also implemented the following using vector:
class MinStack {public: vector
allVec; vector
minVec; void push(int x) { if (allVec.empty()) { allVec.push_back(x); minVec.push_back(x); } else { if (x <= minVec[minVec.size() - 1]) { minVec.push_back(x); } allVec.push_back(x); } } void pop() { if (allVec[allVec.size() - 1] == minVec[minVec.size() - 1]) minVec.erase(minVec.end() - 1); allVec.erase(allVec.end() - 1); } int top() { return allVec[allVec.size() - 1]; } int getMin() { return minVec[minVec.size() - 1]; }};
However, vector is less efficient ......