题目:定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。要求函数min、push以及pop的时间复杂度都是O(1)。
思路:最初以为不就push进来,对比一下已有的,再标记当前最小的嘛。。后来发现,pop出去的时候,有可能min就不同了,恢复不了之前min的值,囧。
应该再开辟一个栈(称为栈B),栈B和原栈(称为栈A)同步push,同步pop,且栈B的顶是栈A最小值的index,这样同步push和pop就能保证一直维护这这个min
代码:
#include <stdio.h> #include <iostream> #include <memory.h> struct stack{ int arr[100]; int min[100]; //记录栈中最小值的index int top; stack(){ top=-1; memset(min,0,sizeof(min)); } void push(int d){ if(top>=100) exit(1); else{ arr[++top] = d; if(top>0) min[top] = d<arr[top-1]?top:(top-1); } } int pop(){ if(top<0) exit(1); else{ return arr[top--]; } } int mymin(){ return arr[min[top]]; } }; int main(){ stack s; s.push(3); printf("%d\n",s.mymin()); s.push(4); printf("%d\n",s.mymin()); s.push(2); printf("%d\n",s.mymin()); s.push(1); printf("%d\n",s.mymin()); s.pop(); printf("%d\n",s.mymin()); s.pop(); printf("%d\n",s.mymin()); s.push(0); printf("%d\n",s.mymin()); return 0; }
浙公网安备 33010602011771号