原题目:https://leetcode-cn.com/problems/min-stack-lcci/
思路:
使用两个vector记录数字和最小数字。index记录数组中元素的个数。
代码:
class MinStack {
int index = 0;
vector<int> nums,minn;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
nums.push_back(x);
if(index == 0) minn.push_back(x);
else minn.push_back(min(minn[index-1],x));
++index;
}
void pop() {
nums.pop_back();
minn.pop_back();
index--;
}
int top() {
return nums[index-1];
}
int getMin() {
return minn[index-1];
}
};