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.
Perhaps, this is the most lazy way.....I will update other methods later.
#include <iostream>
#include <stack>
using namespace std;
class MinStack{
private:
struct value {
int data;
int currMin;
};
stack<value> nodes;
public:
void push(int x) {
if(nodes.empty()) {
nodes.push({x, x});
} else {
value tmp;
tmp.data = x;
tmp.currMin = min(x, nodes.top().currMin);
nodes.push(tmp);
}
}
void pop() {
nodes.pop();
}
int top() {
return nodes.top().data;
}
int getMin() {
return nodes.top().currMin;
}
};
int main(void) {
MinStack myStack;
myStack.push(1);
myStack.push(2);
cout << myStack.getMin() << endl;
myStack.push(0);
cout << myStack.getMin() << endl;
}
A much much better way: getMin takes O(1) time, O(1) space. (This idea is fantastic!)
Idea:
when push a value, compare it with currMin, if it is bigger than currMin, push it without update currMin, if it is smaller, push 2 * value - currMin (notice that this value is also less then currMin, (value + value - currMin)), at the same time, update the currMin into value.
When we pop a value, compare it iwth currMin, if it is bigger than currMin, pop it without update currMin, if it is smaller than currMin, we need to recover the currMin. So in our push process, the current top value : y = 2 * value - currMin, value = currMin, if we want to recover the previous currMin, we need to use 2 * currMin - top value.
#include <iostream>
#include <stack>
using namespace std;
class minStack {
private:
stack<int> currStack;
int minValue;
public:
int currMin() {
if(currStack.empty()) return -1;
else {
return minValue;
}
}
void stackPush(int value) {
if(currStack.empty()) {
currStack.push(value);
minValue = value;
} else {
if(value > minValue) {
currStack.push(value);
} else {
currStack.push(2 * value - minValue);
minValue = value;
}
}
}
void stackPop() {
if(currStack.empty()) return;
else {
if(currStack.top() > minValue) currStack.pop();
else {
int top = currStack.top();
currStack.pop();
minValue = 2 * minValue - top;
}
}
}
};
int main(void) {
minStack a;
a.stackPush(3);
cout << a.currMin() << endl;
a.stackPush(2);
cout << a.currMin() << endl;
a.stackPush(1);
a.stackPop();
cout << a.currMin() << endl;
}

764

被折叠的 条评论
为什么被折叠?



