简而言之,题目就是要我们实现一个栈,这个栈能够快速查找最小值,要求时间复杂度O(1),也就是说不能循环暴力查找
思路:
也许很多人一看到这个题目就有思路,就是定义一个min变量,入栈的时候如果元素比min小就更新min
但是这么做会有一个问题,如果最小值被pop怎么办呢?
我们会想让min回到之前的值,之前应该定义一个min_prev变量储存min之前的值,但是这只能保证min只是被pop一次,被pop多次就失效了
所以我们需要记录min的改变历程,即保证min总是能回到之前的值
我们创建一个辅助栈
每次向栈里push时就向辅助栈里push当前最小值,获取最小值时取辅助栈顶元素就可以,这样就实现了O(1)时间复杂度查找最小值
typedef struct {
int* arr;
int top;
int capacity;
}stack;
typedef struct {
stack s1;
stack s2;
} MinStack;
void StackInit(stack* s)
{
assert(s);
s->arr = NULL;
s->top = 0;
s->capacity = 0;
}
void StackPush(stack* s, int x)
{
assert(s);
if (s->top == s->capacity)
{
int newcapacity = s->capacity == 0 ? 4 : s->capacity * 2;
s->arr = (int*)realloc(s->arr, sizeof(int) * newcapacity);
s->capacity = newcapacity;
}
s->arr[s->top++] = x;
}
int StackTop(stack* s)
{
return s->arr[s->top - 1];
}
void StackPop(stack* s)
{
assert(s);
s->top--;
}
void StackDestroy(stack* s)
{
assert(s);
free(s->arr);
}
MinStack* minStackCreate() {
MinStack* newstack = (MinStack*)malloc(sizeof(MinStack));
StackInit(&newstack->s1);
StackInit(&newstack->s2);
return newstack;
}
void minStackPush(MinStack* obj, int val) {
StackPush(&obj->s1, val);
if ((obj->s1).top == 1)
{
StackPush(&obj->s2, val);
}
else
{
if (StackTop(&obj->s2) > val)
StackPush(&obj->s2, val);
else
StackPush(&obj->s2, StackTop(&obj->s2));
}
}
void minStackPop(MinStack* obj) {
StackPop(&obj->s1);
StackPop(&obj->s2);
}
int minStackTop(MinStack* obj) {
return StackTop(&obj->s1);
}
int minStackGetMin(MinStack* obj) {
return StackTop(&obj->s2);
}
void minStackFree(MinStack* obj) {
StackDestroy(&obj->s1);
StackDestroy(&obj->s2);
free(obj);
}