因为昨天刚学习了栈的实现,使用数组封装成栈,所以,直接想到的思路就是通过数组封装。代码虽然通过,但是用时400ms,很长。
先贴下原始代码,后续再改动优化。
class MinStack {
/** initialize your data structure here. */
int size;
int[] array;
public MinStack() {
array = new int[100];
size = 0;
}
public void resize(int newCapacity){
int[] newArray = new int[newCapacity];
for(int i = 0 ; i<size ; i++){
newArray[i] = array[i];
}
this.array = newArray;
}
public void push(int x) {
if(size == array.length){
resize(2*array.length);
}
array[size] = x;
size++;
}
public void pop() {
if(size != 0){
array[size-1] = 0;
size--;
}
}
public int top() {
if(size != 0){
return array[size-1];
}
else{
return 0;
}
}
public int getMin() {
int temp;
temp = array[0];
for(int i = 0 ; i < size ; i++){
if(array[i] < temp){
temp = array[i];
}
}
return temp;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
另外的一种方法:使用两个栈,一个是题目要求的,另外一个是用来存放最小值的,使用库:
private Stack<Integer> stack = new Stack<>();
private Stack<Integer> minStack = new Stack<>();
public MinStack() {
}
public void push(int x){
stack.push(x);
if(minStack.isEmpty() || minStack.peek()>= x){
minStack.push(x);
}
}
public void pop(){
int a = stack.pop();
if(minStack.peek() == a){
minStack.pop();
}
}
public int top(){
return stack.peek();
}
public int getMin(){
return minStack.peek();
}