https://leetcode.com/problems/min-stack/description/
Solution 1. One stack
class MinStack {
stack<int> dst;
int mi = INT_MAX;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if(x <= mi) {
dst.push(mi);
mi = x;
}
dst.push(x);
}
void pop() {
if(dst.top() == mi) {
dst.pop();
mi = dst.top();
}
dst.pop();
}
int top() {
return dst.top();
}
int getMin() {
return mi;
}
};
or, push the min every time pushing a new element.
class MinStack {
stack<int> dst;
int mi = INT_MAX;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
dst.push(mi);
if(x <= mi) mi = x;
dst.push(x);
}
void pop() {
dst.pop();
mi = dst.top();
dst.pop();
}
int top() {
return dst.top();
}
int getMin() {
return mi;
}
Solution 2. Two stacks.
class MinStack {
stack<int> dst;
stack<int> mst;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
int mi;
if(dst.empty()) mi = x;
else mi = min(mst.top(), x);
mst.push(mi);
dst.push(x);
}
void pop() {
dst.pop();
mst.pop();
}
int top() {
return dst.top();
}
int getMin() {
return mst.top();
}
};
No comments:
Post a Comment