一、题目说明
题目155. Min Stack,设计一个栈,包括push, pop, top, getMin,时间复杂度要求是常数。难度是Easy!
二、我的解答
老老实实用数组实现一个栈,难度不大。关键在于overflowProcess的处理,pop的时候,计算最小值。
class MinStack {
public:
/** initialize your data structure here. */
MinStack(int sz=100):maxSize(sz),topData(-1) {
data = new int[maxSize];
minNum = INT_MAX;
increment = 100;
}
void push(int x) {
if(topData==maxSize-1){
overflowProcess();
}
data[++topData] = x;
if(x<minNum) minNum = x;
}
void pop() {
if(topData>=0){
topData--;
updateMin();
}else{
return;
}
}
void updateMin(){
if(topData<0){
minNum = INT_MAX;
return;
}
int t = topData;
minNum = data[topData];
while(t>=0){
if(data[t]<minNum){
minNum = data[t];
}
t--;
}
}
int top() {
if(topData>=0){
return data[topData];
}
return -1;
}
int getMin() {
return minNum;
}
void overflowProcess(){
int * newData = new int[maxSize+increment];
for(int i=0;i<=topData;i++){
newData[i] = data[i];
}
maxSize += increment;
delete []data;
data = newData;
}
private:
int* data;
int minNum;
int maxSize;
int increment;
int topData;
};
性能如下:
Runtime: 36 ms, faster than 40.56% of C++ online submissions for Min Stack.
Memory Usage: 18.3 MB, less than 5.45% of C++ online submissions for Min Stack.
三、优化措施
其他解答方法,包括用2个stack,或者stack+linklist等。如果数据用vector存储,就不用考虑溢出。