题目及用例
package pid155;
/* 最小栈
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) -- 将元素 x 推入栈中。
pop() -- 删除栈顶的元素。
top() -- 获取栈顶元素。
getMin() -- 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
*/
public class main {
public static void main(String[] args) {
int[][] testTable = {{1,-2,3},{2,7,9,-3,1},{7,10,4,3,1},{11,6,2,7}};
for (int[] ito : testTable) {
test(ito);
}
}
private static void test(int[] ito) {
MinStack solution = new MinStack();
int rtn;
long begin = System.currentTimeMillis();
for (int i = 0; i < ito.length; i++) {
System.out.print(ito[i]+" ");
solution.push(ito[i]);
}
System.out.println();
//开始时打印数组
rtn = solution.top();//执行程序
long end = System.currentTimeMillis();
System.out.println(": rtn=" +rtn);
rtn = solution.getMin();//执行程序
System.out.println(": rtn=" +rtn);
System.out.println();
System.out.println("耗时:" + (end - begin) + "ms");
System.out.println("-------------------");
}
}
解法1(成功,115ms,较慢)
由于用常数时间得到最小值,显然要以空间换时间
设置两个stack,一个为数的stack,一个为此时min的stack
插入一个数,如果它比min的top都小,则min add 它 否则 add min的top
package pid155;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
class MinStack {
List<Integer> list;
List<Integer> minList;
int length;
/** initialize your data structure here. */
public MinStack() {
list=new LinkedList<Integer>();
minList=new LinkedList<Integer>();
length=0;
}
public void push(int x) {
list.add(x);
if(length==0){
minList.add(x);
}
else{
if(x<minList.get(length-1)){
minList.add(x);
}
else{
minList.add(minList.get(length-1));
}
}
length++;
}
public void pop() {
list.remove(length-1);
minList.remove(length-1);
length--;
}
public int top() {
return list.get(length-1);
}
public int getMin() {
return minList.get(length-1);
}
}
/**
* 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();
*/
别人的的解法中不用list和linkedlist 而是用java中的stack类
解法2(成功,105s,较快)
在入栈时,如果这个元素小于等于最小值,那么,我们让最小值入栈,然后将元素值赋给最小值,即新的最小值,然后正常将这个元素入栈;在出栈时,如果栈顶元素与最小值相等,说明他的下一个元素是之前push的最小值(上一个),出栈后,将这个之前的最小值赋值给最新的最小值。(每次push进去的最小值都是下面元素的最小值)
class MinStack {
Stack<Integer> stack=new Stack<>();
int min=Integer.MAX_VALUE;
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if(x<=min){
stack.push(min);
min=x;
}
stack.push(x);
}
public void pop() {
Integer result=stack.pop();
if(result==min){
min=stack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}