题目:Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.
翻译:设计一个含有 push、pop、top、getMin功能的栈,各功能详细说明如下:
push(x) – 将数据x压入栈;
pop() – 将数据弹出;
top() – 获得栈顶数据;
getMin() – 获得栈中最小元素。
思路一—失败的方法
失败方法1:用数组来实现栈,但提交后报错:error: constructor MinStack in class MinStack cannot be applied to given types;
可能原因:因为用数组来实现的栈,所以在初始化栈时需要给出栈的大小,可能因为这样与题目要求不符。
失败方法2:在方法1的基础上将数组换成ArrayList,不会报上述错误了,但总是显示超时。
可能原因:在实现getMin()函数时,需要对ArrayList进行遍历,可能耗时比较长
思路二–可实现
定义两个栈(可以用ArrayList,也可以用Stack实现),一个正常存储数据,记为data,一个只有当需要存入的数据小于或等于栈顶数据时才存入,记为minData;出栈时,data可直接出栈,而只有当data栈顶元素与minData栈顶元素相等时,minData才会弹出元素;通过这种方法可以保证minData中的栈顶元素始终是整个栈的最小数据。
例如:
push(4) –>data={4} ; minData={4};
push(4) –>data&#