
这个题用两个stack的方式其实很简单,解题思路显而易见,一个stack存正常的值,一个stack存最小值,代码如下:
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
s.push(x);
if (ms.empty()) {
ms.push(x);
return;
}
if (ms.top() > x) {
ms.push(x);
} else {
ms.push(ms.top());
}
}
void pop() {
s.pop();
ms.pop();
}
int top() {
return s.top();
}
int getMin() {
return ms.top();
}
private:
stack<int> s;
stack<int> ms;
};
但是,这个题用一个stack也可以解决,怎么解决呢,通过存差值的方式来存储数据,参考代码如下
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if (s.empty()) {
s.push(0);
min = x;
} else {
s.push(x - min);
if (x < min) min = x;
}
}
void pop() {
if (s.empty()) return;
long pop = s.top();
s.pop();
if (pop < 0) min = min - pop;
}
int top() {
long x = s.top();
if (x > 0) return x + min;
else return min;
}
int getMin() {
return min;
}
private:
long min;
stack<long> s;
};
网友评论