第一种方法,暴力法:
typedef struct {
int *stack;
int current_size;
} MinStack;
/** initialize your data structure here. */
MinStack* minStackCreate() {
MinStack *ms=(MinStack*)malloc(sizeof(MinStack));
ms->stack=(int*)malloc(20000*sizeof(int));
ms->current_size=0;
return ms;
}
void minStackPush(MinStack* obj, int x) {
obj->stack[obj->current_size]=x;
obj->current_size++;
}
void minStackPop(MinStack* obj) {
obj->current_size--;
}
int minStackTop(MinStack* obj) {
if (obj->current_size==0) return 0;
else
return obj->stack[obj->current_size-1];
}
int minStackMin(MinStack* obj) {
if (obj->current_size==0) return 0;
int temp=obj->stack[0];
for (int i=0;i<obj->current_size;++i) {
if (obj->stack[i]<temp)
temp=obj->stack[i];
}
return temp;
}
void minStackFree(MinStack* obj) {
free(obj->stack);
free(obj);
}
/**
* Your MinStack struct will be instantiated and called as such:
* MinStack* obj = minStackCreate();
* minStackPush(obj, x);
* minStackPop(obj);
* int param_3 = minStackTop(obj);
* int param_4 = minStackMin(obj);
* minStackFree(obj);
*/
leedcode通过:
执行用时:96 ms, 在所有 C 提交中击败了11.20% 的用户
内存消耗:12.8 MB, 在所有 C 提交中击败了61.38% 的用户
第二种方法,使用两个栈
typedef struct {
int *stack;
int *min_stack;
int current_size;
} MinStack;
/** initialize your data structure here. */
MinStack* minStackCreate() {
MinStack *ms=(MinStack*)malloc(sizeof(MinStack));
ms->stack = (int*)malloc(8000*sizeof(int));
ms->min_stack = (int*)malloc(8000*sizeof(int));
ms->current_size = 0;
return ms;
}
void minStackPush(MinStack* obj, int x) {
obj->stack[obj->current_size]=x;
if (obj->current_size==0) {
obj->min_stack[obj->current_size]=x;
}
else {
if (x < obj->min_stack[obj->current_size-1]) {
obj->min_stack[obj->current_size]=x;
}
else {
obj->min_stack[obj->current_size]=obj->min_stack[obj->current_size-1];
}
}
obj->current_size++;
}
void minStackPop(MinStack* obj) {
if (obj->current_size!=0)
obj->current_size--;
}
int minStackTop(MinStack* obj) {
if (obj->current_size!=0)
return obj->stack[obj->current_size-1];
return 0;
}
int minStackMin(MinStack* obj) {
if (obj->current_size!=0)
return obj->min_stack[obj->current_size-1];
return 0;
}
void minStackFree(MinStack* obj) {
free(obj->stack);
free(obj->min_stack);
free(obj);
}
/**
* Your MinStack struct will be instantiated and called as such:
* MinStack* obj = minStackCreate();
* minStackPush(obj, x);
* minStackPop(obj);
* int param_3 = minStackTop(obj);
* int param_4 = minStackMin(obj);
* minStackFree(obj);
*/
leedcode通过:
执行用时:24 ms, 在所有 C 提交中击败了90.57% 的用户
内存消耗:12.7 MB, 在所有 C 提交中击败了66.92% 的用户