155.最小栈
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
以后这类水题不再发博客了,浪费时间
示例:
输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
输出:
[null,null,null,null,-3,null,0,-2]
解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
提示:
pop、top 和 getMin 操作总是在 非空栈 上调用。
其实就是实现一个能获取最小值的栈。
蛮力搜索其实也能过,目前最大数据也只是8000个不到的操作吧,直接开10000的数组存就完事。
蛮力数组搜索
class MinStack {
public:
int len=0; //长度
int mystack[10100];
/** initialize your data structure here. */
MinStack() {
len=0; //长度
for(int i=0;i<10100;i++)
mystack[i]=0;
}
void push(int x) {
if(x)
mystack[len]=x;
len++;
}
void pop() {
mystack[len]=NULL;
len--;
}
int top() {
return mystack[len-1];
}
int getMin() {
int res=INT_MAX;
for(int i=0;i<len;i++)
if(mystack[i]<res) res=mystack[i];
return res;
}
};
指针法–每个节点都存val与当前最小val,空间换时间
class MinStack {
private:
struct Node {
int val=0;
int min=INT_MAX;
Node *next=NULL;
};
public:
Node *head = new Node;
void push(int x) {
Node *node = new Node;
node->val = x;
node->min = head->min < x ? head->min : x;
node->next = head;
head = node;
}
void pop() {
head = head->next;
}
int top() {
return head->val;
}
int getMin() {
return head->min;
}
};
辅助栈–用第二个栈来存储最小值,空间换时间避免蛮力搜
class MinStack {
public:
stack<int> num_stack;
stack<int> min_stack;
/** initialize your data structure here. */
MinStack() {
min_stack.push(INT_MAX);
}
void push(int x) {
num_stack.push(x);
if(x<min_stack.top())
min_stack.push(x);
else
min_stack.push(min_stack.top());
}
void pop() {
num_stack.pop();
min_stack.pop();
}
int top() {
return num_stack.top();
}
int getMin() {
return min_stack.top();
}
};