题目: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={4,4} ; minData={4,4};
push(5) –>data={4,4,5}; minData={4,4};
push(3) –>data={4,4,5,3}; minData={4,4,3};
pop() –> data={4,4,5}; minData={4,4};
pop() –>data={4,4}; minData={4,4};
代码(java)–此处用的是Stack实现,用ArrayList也可以,但会稍微比Stack臃肿一些
import java.util.*;
class MinStack {
Stack<Integer> data = new Stack<Integer>();
Stack<Integer> minData = new Stack<Integer>();
public void push(int x) {
data.push(x);
if(minData.isEmpty()||x <= minData.peek()){
minData.push(x);
}
}
public void pop() {
if(!data.isEmpty()){
int top = data.pop();
if(top == minData.peek()){
minData.pop();
}
}
}
public int top() {
if(!data.isEmpty()){
return data.peek();
}else{
return 0;
}
}
public int getMin() {
if(!minData.isEmpty()){
return minData.peek();
}else{
return 0;
}
}
}
找的另一种思路的代码
class MinStack {
Node top = null;
public void push(int x) {
if (top == null) {
top = new Node(x);
top.min = x;
} else {
Node temp = new Node(x);
temp.next = top;
top = temp;
top.min = Math.min(top.next.min, x);
}
}
public void pop() {
top = top.next;
return;
}
public int top() {
return top == null ? 0 : top.val;
}
public int getMin() {
return top == null ? 0 : top.min;
}
}
class Node {
int val;
int min;
Node next;
public Node(int val) {
this.val = val;
}
}